Access to 'data-' attribute without jQuery

Is it possible to access the data attribute without jQuery?

Easy with jQuery, but I don’t see anywhere else how to do it without jQuery.

If I search on Google "without jQuery," all I get is jQuery examples.

Is it possible?

+45
javascript
Apr 09 '13 at 20:50
source share
4 answers

In here I found this example:

<div id='strawberry-plant' data-fruit='12'></div> <script> // 'Getting' data-attributes using getAttribute var plant = document.getElementById('strawberry-plant'); var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12' // 'Setting' data-attributes using setAttribute plant.setAttribute('data-fruit', '7'); // Pesky birds </script> 

So it would look very doable.

+72
Apr 09 '13 at 20:52
source share

You can use the dataset attribute. How in:

 element = document.getElementById("el"); alert(element.dataset.name); // element.dataset.name == data-name 
+20
Apr 09 '13 at 20:55 on
source share

This is just an attribute ... use getAttribute as with any other attribute: https://developer.mozilla.org/en/docs/DOM/element.getAttribute

Or am I missing the point of your question.

+2
Apr 09 '13 at 20:53 on
source share

I think you can try the following:

 var ele = document.getElementById("myelement"); if (ele.hasOwnProperty("data")) { alert(ele.data); } 

OR use

 alert(ele['data-property']); 
0
Apr 09 '13 at 21:02
source share



All Articles