Douglas Gaskell
Douglas Gaskell

Reputation: 10030

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.

Upvotes: 2

Views: 808

Answers (4)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

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

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.

Upvotes: 3

Moneer Kamal
Moneer Kamal

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

Saiqul Haq
Saiqul Haq

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

Ivnhal
Ivnhal

Reputation: 1095

Try:

$('.start').parent().parent().find('.end');

Upvotes: 0

Related Questions