Douglas Gaskell Douglas Gaskell - 2 months ago 6
HTML Question

JQuery how to find the closest element that is neither a parent nor a child of the current element?

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.

Answer

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);

DEMO

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.

Comments