Reputation: 694
So I have this HTML code
<section class="panel">
<header class="panel-heading" id="tills">
<div class="panel-actions">
<a href="#" class="fa fa-caret-down"></a>
</div>
<h2 class="panel-title">Tills</h2>
</header>
<div class="panel-body">
<div class="app-next"><button>Next</button></div>
</div>
</section>
I am trying to change the class of <a>
within <div class="panel-actions">
.
$(".panel").on("click", '.app-next button', function(){
var panel;
var target;
panel = $(this).closest('.panel');
target = $(panel).closest('.fa-caret-down');
console.log(panel); //Returns OK.
console.log(target); //Returns <button>
});
Why is console.log(target)
not returning <a href="#" class="fa fa-caret-down">
?
Upvotes: 0
Views: 86
Reputation: 171669
closest()
looks for ancestors up the DOM tree, but you want to look for descendents of .panel
Use find()
to look for descendents.
$(".panel").on("click", '.app-next button', function(){
var $panel =$(this).closest('.panel');
var $target = $panel.find('.fa-caret-down');
console.log($target); //Returns <button>
});
Note that it is redundant and inefficient to wrap an existing jQuery object in $()
. In your code panel
is already a jQuery object that can use jQuery methods
Upvotes: 2
Reputation: 43
.closest() only travels upwards, not downwards.
The code you're looking for is:
target = $('.fa-caret-down',panel);
This is equivalent to saying "look for .fa-caret-down inside panel"
Upvotes: 0
Reputation: 33218
You have to read how .closest() works.
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
You can use .find():
$(panel).find('a.fa-caret-down');
Upvotes: 0
Reputation: 85545
fa-caret-down
is children of the panel
and the closest do not select the selector that way, the closest method select closest parent div. You may use find method instead:
target = $(panel).find('.fa-caret-down');
Upvotes: 0