adamdehaven
adamdehaven

Reputation: 5920

Select next element with class with jQuery

For the sake of making this simple, I have two "Featured" blocks, and the first one loads with the class features-active applied.

After a timer (in jQuery), I would like to remove the features-active class from the first element, and apply it to the next block with the .features class.

Here's my HTML:

<!-- Feature 1 -->

<div class="span3">
  <div class="features drop-shadow features-active">
    <h4><strong>SUPER</strong> RESPONSIVE</h4>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua Lorem ipsum dolor sit amet...</p>
  </div>
</div>

<!-- Feature 2 -->

<div class="span3">
  <div class="features drop-shadow">
    <h4><strong>SUPER</strong> RESPONSIVE</h4>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua Lorem ipsum dolor sit amet...</p>
  </div>
</div>

My only question (I feel retarded today) is - After my timer fires, how do I select the next .features element that comes after the div.features-active ?

Here's my jQuery that does not work:

var nextFeature = $('div.features-active').next('div.features');

Upvotes: 1

Views: 4847

Answers (5)

j08691
j08691

Reputation: 207861

Instead of all the wasted overhead by using .next(), .parent(), .children(), .find(), etc, just use the index of the featured elements.

var idx = 1;
setInterval(function () {
    $('div.features').removeClass('features-active');
    $('div.features').eq(idx).addClass('features-active');
    idx++;
}, 2000);

jsFiddle example

Upvotes: 1

Jai
Jai

Reputation: 74738

I think you are looking for this: http://jsfiddle.net/umTPw/

setTimeout(function () {
   $('.features').removeClass('features-active').promise().done(function () {
      $(this).parent().next().find('.features').addClass('features-active');
   });
}, 2000);

Upvotes: 0

Alexander
Alexander

Reputation: 23537

You need to apply .next() on the node's parent.

var nextFeature = $('div.features-active').parent('div.span3')
                                          .next('div.span3')
                                          .children('div.features');

Upvotes: 3

uv_man
uv_man

Reputation: 224

How about this:

var nextFeature = $('div.features-active').next().find('div.features');

Upvotes: -1

adeneo
adeneo

Reputation: 318162

There is no next .features, they have different parents ?

var nextFeature = $('div.features-active').closest('.span3')
                                          .next('.span3')
                                          .find('div.features')

Upvotes: 1

Related Questions