Access 'data-' attribute without jQuery

You could use the dataset attribute. As in:

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

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.


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.

Tags:

Javascript