Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html "data-" attribute as javascript parameter

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?

like image 552
Werner Avatar asked May 15 '13 13:05

Werner


People also ask

Can data attributes be used with JavaScript?

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).

How can I get the values of data attributes in JavaScript code?

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.

Can data -* attribute contain HTML tags?

Certainly. Entities are converted into their values when parsed.


1 Answers

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
like image 168
Ian Avatar answered Sep 26 '22 04:09

Ian