Reputation: 1875
How can I get the the Nth parent of multiple elements?
Right now I do it like this:
var winners = THUMBNAILS.find(".tournament-winner:contains(" + filter + ")");
var filteredThumbnails = winners.parent().parent().parent().parent().clone();
this does work.
But when I try to do it like:
var filteredThumbnails = winners.parents().eq(3).clone();
It only gets the thumbnail (great grandfather) of just one element in the winners
variable.
Is there any easier way to get Nth parent of multiple elements?
Upvotes: 0
Views: 704
Reputation: 3600
You can also use filter
on return value of parents.
$.parents
return an array.
Let's say you have the following HTML and you want to get divs with ids parentN
. which is the third parent. After that you can convert the elements to an array. Alternatively, you can create a function like this and use it in different places.
then you have to get every fourth element of the parents
function getNthParents(obj, N) {
return obj.parents().filter(index => !((index + 1) % N)).toArray();
}
nthParents = getNthParents($('.thumbnail'), 3)
console.log(nthParents)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent1'>
<div>
<div>
<div class='thumbnail'>
</div>
</div>
</div>
</div>
<div id='parent2'>
<div>
<div>
<div class='thumbnail'>
</div>
</div>
</div>
</div>
<div id='parent3'>
<div>
<div>
<div class='thumbnail'>
</div>
</div>
</div>
</div>
Upvotes: 0
Reputation: 2415
It would be a lot easier if you shared your html.
As i am not sure what you are trying to achieve...but
Another way of getting up multiple parent levels of the element you are targeting, which doesn't have a unique name would be like below. which will traverse up until it finds a parent which has an id which starts with "parent".
winners.parents("[id^=parent]")
Although i would give them a generic css class to travel up to rather than this.
Upvotes: 0
Reputation: 133403
You can use .add()
Create a new jQuery object with elements added to the set of matched elements.
//Create empty object
var filteredThumbnails = $();
//Iterate and target parent
winners.each(function(){
filteredThumbnails.add($(this).parents().eq(3).clone());
});
Upvotes: 1
Reputation: 6015
write a .map()
or .forEach()
function on the winners array.
example:
filteredThumbnails = winners.map(winner => winner.parent().parent().parent().parent().clone());
Upvotes: 0