Selecting Elements by Data Attribute in jQuery

Selecting elements by data attributes is very easy in jQuery. As with all other attributes, we can simply use the attribute selector. In fact, we do not need to handle the data attribute in any special way, as long as the data attribute is available in the DOM. Please consider the following example.

var matches = $('.news-item[data-news-id="52"]');

In the above example, we select all elements with the class news-item that also have an attribute named data-news-id with a value of 52.

That is really all there is to it.

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *