Lets say I have this:
<div data-uid="aaa" data-name="bbb", data-value="ccc" onclick="fun(this.data.uid, this.data-name, this.data-value)">
And this:
function fun(one, two, three) { //some code }
Well this is not working but I have absolutely no idea why. could someone post a working example please?
HTML data-* Attributes The data-* attributes gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).
We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.
Certainly. Entities are converted into their values when parsed.
The easiest way to get data-*
attributes is with element.getAttribute()
:
onclick="fun(this.getAttribute('data-uid'), this.getAttribute('data-name'), this.getAttribute('data-value'));"
DEMO: http://jsfiddle.net/pm6cH/
Although I would suggest just passing this
to fun()
, and getting the 3 attributes inside the fun
function:
onclick="fun(this);"
And then:
function fun(obj) { var one = obj.getAttribute('data-uid'), two = obj.getAttribute('data-name'), three = obj.getAttribute('data-value'); }
DEMO: http://jsfiddle.net/pm6cH/1/
The new way to access them by property is with dataset
, but that isn't supported by all browsers. You'd get them like the following:
this.dataset.uid // and this.dataset.name // and this.dataset.value
DEMO: http://jsfiddle.net/pm6cH/2/
Also note that in your HTML, there shouldn't be a comma here:
data-name="bbb",
References:
element.getAttribute()
: https://developer.mozilla.org/en-US/docs/DOM/element.getAttribute .dataset
: https://developer.mozilla.org/en-US/docs/DOM/element.dataset .dataset
browser compatibility: http://caniuse.com/dataset 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