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-|
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.
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.
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.
Try this:
var a = $("#p32").prevAll(".slide").not(".subsection").first();
alert($(a).text());
Fiddle here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With