jQuery find element by data attribute value

MrUpsidown picture MrUpsidown · Feb 13, 2014 · Viewed 265.3k times · Source

I have a few elements like below:

<a class="slide-link" href="#" data-slide="0">1</a>
<a class="slide-link" href="#" data-slide="1">2</a>
<a class="slide-link" href="#" data-slide="2">3</a>

How can I add a class to the element which has a data-slide attribute value of 0 (zero)?

I have tried many different solutions but nothing worked. An example:

$('.slide-link').find('[data-slide="0"]').addClass('active');

Any idea?

Answer

Use Attribute Equals Selector

$('.slide-link[data-slide="0"]').addClass('active');

Fiddle Demo

.find()

it works down the tree

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.