jQuery find element by data attribute value

JqueryHtmlCssCustom Data-Attribute

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

You can also use .filter()

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

Solution 3 - Jquery

I searched for a the same solution with a variable instead of the String.
I hope i can help someone with my solution :)

var numb = "3";
$(`#myid[data-tab-id=${numb}]`);

Solution 4 - Jquery

you can also use andSelf() method to get wrapper DOM contain then find() can be work around as your idea

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

.active {
  background: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMrUpsidownView Question on Stackoverflow
Solution 1 - JqueryTushar Gupta - curioustusharView Answer on Stackoverflow
Solution 2 - JqueryAntonView Answer on Stackoverflow
Solution 3 - JqueryAleshaneeView Answer on Stackoverflow
Solution 4 - JqueryGirishView Answer on Stackoverflow