JQuery - find the 1st element with a specific class on top, but not in front of another element

HTML looks something like this:

<li class="divider"> <div> ...(maybe more divs)... <div class="content"> ...(maybe more divs)... <a href="#" class="link">LINK</a> ... 

how can I select .content DIV from jQuery function connected by reference? Please note that I have several lists like this, and some of them may not have a div.content, so I want to select this div only if it exists in the current block (li.divider).

I tried with $link.parent().parent().find('content') , but in some cases this does not work, because the number of elements between these two elements can vary ...

+4
source share
3 answers

If they are not nested, you must do this:

 $('a.link').click(function() { $(this).closest('div.content'); }); 

or

 $('a.link').click(function() { $(this).parents('div.content:first'); }); 

If they are nested, you may need to do something like this:

 $('a.link').click(function() { $(this).closest('li.divider').find('div.content'); }); 

... so if the nesting happens and there is no div.content in the current div.content , you cannot select the more distant ancestor of div.content .

+5
source

$link.parent(".content") ?

0
source

Use the closest selector ...

 var parentContent = $(this).closest("div.content"); if(parentContent.length > 0) { alert("DIV was found!"); } 
0
source

Source: https://habr.com/ru/post/1315236/


All Articles