Content 1some other HTML....">

JQuery: search previous div

<div class="a" style="display:none">Content 1</div> <div class="a" style="display:none">Content 2</div> some other HTML... <span id="b">foobar</span> 

How can I match the first div class = "a" over span id = "b" to show () this? Id = "b" is the only thing I know before.

+4
source share
4 answers

Like this:

 $('#b').prevAll('.a:first').show(); 
+8
source
 $("#b").closest(".a").show(); 

Try it.

+3
source

Do ancestors share elements? If so, you can combine response letters and SLaks:

 $('#b').closest('parentType').prevAll('.a:first').show(); 

Or something similar, depending on your DOM.

0
source

As long as I understand a few selectors correctly, this should work. It will get all divs with class 'a' and and span with id 'b'. They will be โ€œdocumentedโ€ in accordance with the documentation . Then you need to get the div before your span tag and display it.

 var elems = $('span#b, div.a'); var divIndex; for (var i = 0; i < elems.length; i++) { if (elems[i].tagName == "SPAN") { divIndex = i - 1; break; } } $(elems[divIndex]).show(); 
0
source

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


All Articles