Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  4] [ 3]  / answers: 1 / hits: 130309  / 11 Years ago, wed, may 15, 2013, 12:00:00

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?


More From » html

 Answers
153

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:




[#78221] Tuesday, May 14, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
johnnyblaynes

Total Points: 667
Total Questions: 121
Total Answers: 102

Location: Anguilla
Member since Sat, Jan 23, 2021
3 Years ago
;