Tony
Tony

Reputation: 12695

jQuery How to find the next element with a specific attribute?

I have some label tags on my page, some of them has the myAttr attribute.

I select on of them like $('label[myAttr="lorem"]')

How to find the next label (with the myAttr attribute) after that one ? The value of the myAttr is different for each label tag.

Upvotes: 0

Views: 394

Answers (1)

Matt Ball
Matt Ball

Reputation: 359786

You can select all of the <label>s with that attribute like so:

$('label[myAttr]')

and traverse that collection using .each(). If you've already got that collection, and just want to hop from $('label[myAttr="lorem"]') to the next <label> with that attribute, this will work:

var $labels = $('label[myAttr]');
var $current = $('label[myAttr="lorem"]');
var currentIndex = $labels.index($current);
var $next = $labels.eq(currentIndex + 1);

http://jsfiddle.net/mattball/xZKGk

N.B. I don't recommend doing that in a loop because of its asymptotic runtime behavior.

Upvotes: 4

Related Questions