Data Attributes
Attribute Name
The data attribute name must be at least one character long and must be prefixed with ‘data-
‘. It should not contain any uppercase letters.
Attribute Value
The attribute value can be any string.
<ul id="vegetable-seeds"> <li data-spacing="10cm" data-sowing-time="March to June">Carrots</li> <li data-spacing="30cm" data-sowing-time="February to March">Celery</li> <li data-spacing="32cm" data-sowing-time="March to September">Radishes</li> </ul>
Set & get attribute
<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'); </script>
Proper way:
<div id='sunflower' data-leaves='47' data-plant-height='2.4m'></div>
<script>
// 'Getting' data-attributes using dataset
var plant = document.getElementById('sunflower');
var leaves = plant.dataset.leaves; // leaves = 47;
// 'Setting' data-attributes using dataset
var tallness = plant.dataset.plantHeight; // 'plant-height' -> 'plantHeight'
plant.dataset.plantHeight = '3.6m';
</script>
Remove the data attribute:
plant.dataset.leaves = null;
Select elements:
// Select all elements with a 'data-flowering' attribute document.querySelectorAll('[data-flowering]'); // Select all elements with red leaves document.querySelectorAll('[data-foliage-colour="red"]');
Dataset:
var restaurant = document.getElementById("restaurantId");
var ratings = restaurant.dataset.ratings;
restaurant.dataset.ratings = newRating;
var owner = restaurant.dataset['ownerName'];
restaurant.dataset['ownerName'] = 'newOwner';