subharb
subharb

Reputation: 3472

How to get number of elements of a class before a certain element

I want to know how many elements of a certain class appear in the DOM before an element that let's say has been clicked on.

<html>
  <div class="a">
  </div>
  <div class="b">
      <div class="a">
      </div>
  </div>
  <button>CLick me!</button>
  <div class="a">
  </div>
</html>

So in the previous DOM tree if the element to be clicked is the button, and Im looking for divs with class "a" it should return 2, even though in the whole tree there are 3, but "before" the button there are only 2.

How could I do that?

Thanks

[EDIT] The search of elements starts at the begining of the DOM tree until the clicked element. Don't assume that structure, where the elemets are sibilings of the clicked element, it can have any kind of structture.

Upvotes: 2

Views: 181

Answers (3)

wirey00
wirey00

Reputation: 33661

You can filter with .not()

$('button').click(function(){
    var $this = $(this);
    console.log(
             $('.a')
                   // get all with class=a not including all after..descendants after  
                   .not($this.nextAll('.a'), $('.a',$this.nextAll('*')))
                   // get number of elements returned
                   .length
     );

});​

http://jsfiddle.net/Gz9v2/

Upvotes: 0

Kevin B
Kevin B

Reputation: 95020

Try this, getting all prev elements that match the class, then all children of those prev elements that match the class.

$("button").click(function() {
    var prev = $(this).prevAll(this.className);
    console.log( prev.length + prev.find(this.className).length );
});

not tested though.

Upvotes: 0

Austin Greco
Austin Greco

Reputation: 33544

get all previous nodes matching .a, then get all previous nodes' descendants matching .a and add together:

var count = $('button').prevAll( '.a' ).length;
count += $('button').prevAll().find('.a').length;
console.log( count );

Upvotes: 2

Related Questions