March 5, 2012

jQuery: Select last match before specified element

Question by rampion

Is there a way in jQuery to, given an element and a selector, select the last match of that selector before that element from an in-order traversal of the DOM tree?

For example, given the DOM tree:

<html>
  <body>
    <div class="a" id="div0" />
    <div>
      <div class="a" id="div1"/>
    </div>
    <div class="b" id="div2"/>
    <div id="element"/>
    <div class="a" id="div3"/>
    <div class="b" id="div4"/>
  </body>
</html>

Using the selector .a and element #element, you’d get #div1, and using the selector .b and the element #element, you’d get #div2.

The use case is writing a GreaseMonkey script to work across different versions of Firefox with some slightly mangled HTML. I’ve got an element I can find consistently in all versions, but another element I want to find is either a previous sibling of an ancestor of the element or a descendent of a previous sibling of an ancestor of the element (depending on the version).

All I can really rely on is that it is the last match of the selector that occurs before the element I have when doing an in-order traversal of the DOM tree.

Answer by James Montagne

This should do it, using your first example:

var $collection = $(".a, #element");

var eleIndex = $collection.index($("#element"));

var prevEl = $collection.eq(eleIndex - 1);

alert(prevEl.attr("id"));

http://jsfiddle.net/WdsGa/

Answer by Starx

This should do it

var last = $(".a, #element").eq($(".a, #element").length-1);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!