Access 'data-' attribute without jQuery

Javascript

Javascript Problem Overview


Can I access a data- attribute without jQuery?

It's easy with jQuery, but I can't see anywhere how to do it without jQuery.

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

Is it even possible?

Javascript Solutions


Solution 1 - Javascript

On 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 appear very doable.

Update: Since Microsoft is now (2020) phasing out the old Internet Explorer engine in favour of a Chromium based Edge, the dataset property is likely to work everywhere. The exception will, for a time, be organizations and corporate networks where IE is still forced. At the time of writing this though - jsPerf still shows the get/setAttribute method as being faster than using dataset, at least on Chrome 81.

Solution 2 - Javascript

You could use the dataset attribute. As in:

element = document.getElementById("el");
alert(element.dataset.name); // element.dataset.name == data-name

Solution 3 - Javascript

It's 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.

Solution 4 - Javascript

You can also use:

getAttribute('data-property');

Which is a bit cleaner and easier to read.

This will get the value of the data attribute.

Solution 5 - Javascript

I think you can try this:

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

OR use

alert(ele['data-property']);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2143356View Question on Stackoverflow
Solution 1 - JavascriptfredrikView Answer on Stackoverflow
Solution 2 - JavascripttomorView Answer on Stackoverflow
Solution 3 - JavascriptdrquicksilverView Answer on Stackoverflow
Solution 4 - JavascriptHellodanView Answer on Stackoverflow
Solution 5 - Javascriptasim-ishaqView Answer on Stackoverflow