Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find element by data attribute value

People also ask

How do you find the element based on a data attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

How get value from data attribute in jQuery?

You can use this jquery data() syntax for get data-id attribute value. $("selector"). data("textval"); You can use this jquery data() syntax for get data-textval attribute value.

Which jQuery selector is used to retrieve all elements with the attribute data attribute name?

You can use the attribute selector: $('[data-my-key]').

How do you select an element with specific attributes?

The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!


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.


You can also use .filter()

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

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}]`);

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>