Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 805
Hazem Salama Avatar asked Mar 21 '10 16:03

Hazem Salama


People also ask

How do I select an element with a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

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 set data attribute in jQuery?

To set an attribute and value by using a function using this below syntax. $(selector). attr(attribute,function(index,currentvalue)) ; To set multiple attributes and values using this below syntax.


4 Answers

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>
like image 30
JTG Avatar answered Oct 17 '22 02:10

JTG


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

You should be able to omit the *, but if I recall correctly, depending on which jQuery version you’re using, this might give faulty results.

Note that for compatibility with the Selectors API (document.querySelector{,all}), the quotes around the attribute value (22) may not be omitted in this case.

Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo'), and results in a smaller file size after minification (compared to using .attr('data-foo')).

like image 132
Mathias Bynens Avatar answered Oct 17 '22 00:10

Mathias Bynens


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"]');
like image 149
drzaus Avatar answered Oct 17 '22 00:10

drzaus


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

var elements = document.querySelectorAll('[data-customerID="22"]');

elements[0].innerHTML = 'it worked!';
<a data-customerID='22'>test</a>

Info:

  • data attributes

  • .querySelectorAll();

like image 113
Sjoerd Pottuit Avatar answered Oct 17 '22 00:10

Sjoerd Pottuit