Reputation: 25445
Consider this sample html
<div class="A">
<div class="B">
<span class="C">Sample text</span>
<div class="D">
<div class="E">Clickable Text</div>
</div>
</div>
</div>
And some jQuery
$(".E").click(function(){
//body
});
What is the easiest way to get a parent of $(this)
that matches a selector? For example, say in the example I need to get the div where class="A"
. At the moment because I know the structure of the html I could do
$(this).parent().parent();
But I'm looking for a way that would work regardless of the structure. Something along the lines of
$(this).findFirstParent(".A");
I hope I've been understandable.
Upvotes: 2
Views: 301
Reputation: 14049
First Solution:
$(this).closest('.A')
Source: http://api.jquery.com/closest/ This will return the first parent when traversing that matchs the selector.
Second solution:
$(this).parents('.A:first')
Source: http://api.jquery.com/parents/ This will return all the parents that matches the selectors
Upvotes: 3
Reputation: 1
The jQuery parent selector might help you there. You can combine it with the class you are looking for. See the docs @ http://api.jquery.com/parent-selector/
Upvotes: 0
Reputation: 123387
$(".E").click(function(){
console.log($(this).closest('.A'));
/* console.log($(this).parents('.A')); works fine too */
});
See
http://api.jquery.com/closest/
http://api.jquery.com/parents/
Note that parent()
is different than parents()
method (the first one look for one ancestor only)
Upvotes: 4