I have this working:
<div data-people="australian">Australian people eats...</div>
<script type="text/javascript">
alert($("[data-people=australian]").html());
</script>
But this other doesn't work and I don't know how to solve:
<div id="mich">Australian people eats...</div>
<script type="text/javascript">
$("#mich").data("people", "australian");
alert($("[data-people=australian]").html());
</script>
Why I can't set the data-* HTML5 attributes from jQuery and the use them to select a DOM object???
Lot of thanks
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.
The attr() method in jQuery is used to set or return the attributes and values of the selected elements. To set multiple attributes and values: $(selector). attr({attribute:value, attribute:value, ...})
Creating an HTML Data Attribute Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.
The data-
attribute to jQuery data() mapping is one-direction. You should use the attr() function if you want to actually set the attribute on the node.
$("#mich").attr("data-people", "australian");
From the docs:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With