Reputation: 10030
Say I have HTML that looks like this:
<div>
<div>
<div class="calendar start">
</div>
</div>
<div>
<div class="calendar end">
</div>
</div>
</div>
We can assume that the start
and end
will always be on the same "level" of a branch from each other, and will at some point share a common parent.
Without knowledge of the exact HTML structure, how would I find calendar end
from calendar start
? What if they are nested further down?
Edit: For clarification. I want to start at start
's parent. Search all child elements for end
. Then move to the next parent, and search all child elements...etc till I find end
. I am wondering if this is possible with built in JQuery functions, without writing my own DOM traversal logic.
Upvotes: 2
Views: 808
Reputation: 67197
You can do it like below, But it is a costlier process.
var parentWhichHasCalEnd =
$($(".calendar.start").parents()
.get().find(itm => $(itm).find(".calendar.end").length));
var calEnd = $(".calendar.end", parentWhichHasCalEnd);
Explanation: We are selecting the .start
element first, then we are retrieving its parent elements. After that we are converting that jquery object collection to an array of elements by using .get()
. So that we could use .find()
, an array function over it. Now inside of the callBack of find
we are checking for .end
over each parent element of .start
, if a parent has .end
then we would return that parent. Thats all.
You could get more understanding, if you read .get(), .find(), and arrow functions.
Upvotes: 3
Reputation: 1877
i don't know if i got this right but have you tried children function in jquery
$( ".calender" ).children( ".end" )
and for the parent you can use parent() function so you can first check the parent then the children or vicversa
edit: if you dont know the exact structure the better way is to find the common parent and then search it's children :
$( ".calender.start").closest('.common-parent').children('.calender.end');
closest function give the nearest parent
Upvotes: 1
Reputation: 2397
You can use jQuery#next()
method from .start
parent element
var startSelector = $('body > div > div:nth-child(3) > .start')
var endSelector = secondStart.parent().next().find('.end');
I think this method is faster rather than jQuery#children()
method, but you can benchmark it if you want to
btw you may check my answer based on this JSBin
Upvotes: 1