Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery find closest previous sibling that does not have class

Tags:

jquery

dom

css

I am stumped at trying to get the closest previous element with class 'slide' that does NOT contain class 'subsection' using jQuery

Sample HTML:

<section id="p1" class="slide"></section>
<section id="p2" class="slide"></section>
<section id="p3" class="slide"></section> <!--I AM TRYING TO GET THIS ELEM -->
<section id="p31" class="slide subsection"></section>
<section id="p32" class="slide subsection"></section> <!--I AM HERE -->
<section id="p4" class="slide"></section>

I have tried: (where $subsection is the element indicated above)

var $slide = $subsection.prev('.slide').not('.subsection');
var $slide = $subsection.prev('.slide:not(".subsection")');
var $slide = $subsection.prev('.slide').not("[class='subsection']");
var $slide = $subsection.prev('.slide:not([class="subsection"])');

Now I found out that prev() only selects a single previous elem and then stops, but prevUntil doesn't work either?

var $slide = $subsection.prevUntil('.slide').not('.subsection');

I also tried:

var $slide = $subsection.prevAll('.slide').not('.subsection');

but this gets me the very first slide element with id p1.

If anyone has any tips I'd appreciate it... Can anyone stop me going cray cray? 8-|

like image 915
Natacha Beaugeais Avatar asked Nov 01 '13 08:11

Natacha Beaugeais


People also ask

How can I find previous siblings in jQuery?

jQuery prev() Method The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent. The DOM tree: This method traverse backwards along the previous sibling of DOM elements.

How does closest work in jQuery?

The closest( selector ) method works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression.

What is the use of siblings in jQuery?

The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This is defines for accessing elements in the DOM tree.


1 Answers

Try this:

var a = $("#p32").prevAll(".slide").not(".subsection").first();
alert($(a).text());

Fiddle here.

like image 140
codingrose Avatar answered Nov 08 '22 05:11

codingrose