[jquery] Selecting element by data attribute with jQuery

Is there an easy and straight-forward method to select elements based on their data attribute? For example, select all anchors that has data attribute named customerID which has value of 22.

I am kind of hesitant to use rel or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.

This question is related to jquery html custom-data-attribute

The answer is


The construction like this: $('[data-XXX=111]') isn't working in Safari 8.0.

If you set data attribute this way: $('div').data('XXX', 111), it only works if you set data attribute directly in DOM like this: $('div').attr('data-XXX', 111).

I think it's because jQuery team optimized garbage collector to prevent memory leaks and heavy operations on DOM rebuilding on each change data attribute.


For people Googling and want more general rules about selecting with data-attributes:

$("[data-test]") will select any element that merely has the data attribute (no matter the value of the attribute). Including:

<div data-test=value>attributes with values</div>
<div data-test>attributes without values</div>

$('[data-test~="foo"]') will select any element where the data attribute contains foo but doesn't have to be exact, such as:

<div data-test="foo">Exact Matches</div>
<div data-test="this has the word foo">Where the Attribute merely contains "foo"</div>

$('[data-test="the_exact_value"]') will select any element where the data attribute exact value is the_exact_value, for example:

<div data-test="the_exact_value">Exact Matches</div>

but not

<div data-test="the_exact_value foo">This won't match</div>

Native JS Examples

Get NodeList of elements

var elem = document.querySelectorAll('[data-id="container"]')

html: <div data-id="container"></div>

Get the first element

var firstElem = document.querySelector('[id="container"]')

html: <div id="container"></div>

Target a collection of nodes which returns a nodelist

document.getElementById('footer').querySelectorAll('[data-id]')

html:

<div class="footer">
    <div data-id="12"></div>
    <div data-id="22"></div>
</div>

Get elements based on multiple (OR) data values

document.querySelectorAll('[data-section="12"],[data-selection="20"]')

html:

<div data-selection="20"></div>
<div data-section="12"></div>

Get elements based on combined (AND) data values

document.querySelectorAll('[data-prop1="12"][data-prop2="20"]')

html:

<div data-prop1="12" data-prop2="20"></div>

Get items where the value starts with

document.querySelectorAll('[href^="https://"]')

I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.

_x000D_
_x000D_
var elements = document.querySelectorAll('[data-customerID="22"]');_x000D_
_x000D_
elements[0].innerHTML = 'it worked!';
_x000D_
<a data-customerID='22'>test</a>
_x000D_
_x000D_
_x000D_

Info:


Using $('[data-whatever="myvalue"]') will select anything with html attributes, but in newer jQueries it seems that if you use $(...).data(...) to attach data, it uses some magic browser thingy and does not affect the html, therefore is not discovered by .find as indicated in the previous answer.

Verify (tested with 1.7.2+) (also see fiddle): (updated to be more complete)

var $container = $('<div><div id="item1"/><div id="item2"/></div>');

// add html attribute
var $item1 = $('#item1').attr('data-generated', true);

// add as data
var $item2 = $('#item2').data('generated', true);

// create item, add data attribute via jquery
var $item3 = $('<div />', {id: 'item3', data: { generated: 'true' }, text: 'Item 3' });
$container.append($item3);

// create item, "manually" add data attribute
var $item4 = $('<div id="item4" data-generated="true">Item 4</div>');
$container.append($item4);

// only returns $item1 and $item4
var $result = $container.find('[data-generated="true"]');

For this to work in Chrome the value must not have another pair of quotes.

It only works, for example, like this:

$('a[data-customerID=22]');

via Jquery filter() method:

http://jsfiddle.net/9n4e1agn/1/

HTML:

<button   data-id='1'>One</button>
<button   data-id='2'>Two</button>

JavaScript:

$(function() {    
    $('button').filter(function(){
        return $(this).data("id")   == 2}).css({background:'red'});  
     });

It's sometimes desirable to filter elements based on whether they have data-items attached to them programmatically (aka not via dom-attributes):

$el.filter(function(i, x) { return $(x).data('foo-bar'); }).doSomething();

The above works but is not very readable. A better approach is to use a pseudo-selector for testing this sort of thing:

$.expr[":"].hasData = $.expr.createPseudo(function (arg) {
    return function (domEl) {
        var $el = $(domEl);
        return $el.is("[" + ((arg.startsWith("data-") ? "" : "data-") + arg) + "]") || typeof ($el.data(arg)) !== "undefined";
    };
});

Now we can refactor the original statement to something more fluent and readable:

$el.filter(":hasData('foo-bar')").doSomething();

To select all anchors with the data attribute data-customerID==22, you should include the a to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.

$('a[data-customerID="22"]');

Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:

  • pure/plain JS with querySelector (uses CSS-selectors):
    • select the first in DOM: document.querySelector('[data-answer="42"],[type="submit"]')
    • select all in DOM: document.querySelectorAll('[data-answer="42"],[type="submit"]')
  • pure/plain CSS
    • some specific tags: [data-answer="42"],[type="submit"]
    • all tags with an specific attribute: [data-answer] or input[type]

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to custom-data-attribute

How can I get the values of data attributes in JavaScript code? jQuery: get data attribute jQuery find element by data attribute value Using HTML data-attribute to set CSS background-image url Adding data attribute to DOM Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error? How to set data attributes in HTML elements jQuery Data vs Attr? Unable to set data attribute using jQuery Data() API Select elements by attribute in CSS