Get parent element and find button element and replace its text
I have these codes.
Html
<div class="has_dropdown">
<button>Select branch</button>
<ul class="dropdownmenu">
<li><a href="#">Branch 1</li>
<li><a href="#">Branch 2</li>
<li><a href="#">Branch 3</li>
</ul>
</div>
and this jquery script
$('.dropdownmenu li a').click(function(){
//go to the .has_dropdown which is the parent container and find button element within it and then replace the text of it with the current click anchor element text.
$(this).parent('.has_dropdown').find('button').text($(this).text());
});
as you can see from the script code, it will go to the parent .has_dropdown and then find the button element inside it and then replace the button element text with the text of the current clicked element (. dropdownmenu li a), but unfortunately doesn't work. Any hints, ideas, suggestions, recommendations for getting this job done?
source to share
This is because the element is .has_dropdown
not the direct parent of the element <a>
. You need to use .closest()
method instead .
$('.dropdownmenu li a').click(function(){
$(this).closest('.has_dropdown').find('button').text($(this).text());
});
The method .parent()
navigates to its immediate parent while walking through its ancestors. .closest
source to share