Access ‘data-‘ attribute without jQuery

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.

Leave a Comment