timpone
timpone

Reputation: 19979

how to select next instance of a selector with possibly intervening classes

I'd like to be able to select the next instance of a specific selector such as .ajax-loader in the following. I tried .next('.ajax-loader') but didn't seem to work and since there could be intervening classes, just simply next() wouldn't work. Here's my markup and a fiddle:

$(document).ready(function(){
  $('.click-me').on('click',function(){
    $(this).next().html('here i am');
  });
});​

html:

<button class='click-me'>JT</button>
<div class='other-loader'>other loader</div><div class='ajax-loader'></div><br />
<button class='click-me'>JU</button><div class='ajax-loader'></div><br />

In the first example, how could I progamatically say the next instance of ajax-loader? Here is a fiddle: http://jsfiddle.net/HAJLP/2/

thx in advance

Upvotes: 0

Views: 62

Answers (3)

Mutant
Mutant

Reputation: 3821

This one will be less costly, as you traversing thru only div tags -

$(document).ready(function(){
  $('.click-me').on('click',function(){
      $(this).nextAll('div.ajax-loader:first').html('here i am');
  });
});​

Upvotes: 0

gsimoes
gsimoes

Reputation: 1021

Try this:

$(document).ready(function(){
    $('.click-me').on('click',function(){
        $(this).find("~ .ajax-loader:first").html('here i am');
    });
});​

Upvotes: 0

mattn
mattn

Reputation: 7733

Try to use nextAll() with :first.

$(document).ready(function(){
  $('.click-me').on('click',function(){
     $(this).nextAll('.ajax-loader:first').html('here i am');
  });
});​

Upvotes: 1

Related Questions