Data (Key value) can be included for processing by a script using the data-*=“” attributes.
<p data-length="2m" >Beyond The Sea</p>
p::before {
content: attr(data-length) " ";
}
where attr is the css attribute function
With an attribute selector, you can select the nodes with a certain value.
<ul>
<li data-type="blue">Blue</li>
<li data-type="red">Red</li>
</ul>
*[data-type="blue"] {
color: blue;
}
<article
id="electriccars"
data-columns="3"
data-index-number="12314"
data-parent="cars">
</article>
var article = document.getElementById('electriccars');
console.log("Columns: "+article.dataset.columns); // "3"
console.log("Has Columns As Property ?: "+article.dataset.hasOwnProperty("columns")); // true
console.log("Has Columns As Property With In operator ?: "+("columns" in article.dataset)); // true
console.log("Index number: "+article.dataset.indexNumber); // "12314"
console.log("Parent: "+article.dataset.parent); // "cars"
As this is a normal attribute, you add or remove it via the standard DOM attribute manipulation function.
'keyname' in element.dataset
document.body.addEventListener('click', (event) => {
if (event.target.dataset.echo) {
console.log('The target element has a data-echo attribute. Hello '+event.target.dataset.echo+' !')
} else {
console.log('The target element has NOT a data-echo attribute')
}
})
<p><button data-echo="you">Click Me ! (To see that there is a data attribute, that output the `you` value)</button></p>
<p><button>Click Me ! (To see that there is no data attribute on this button)</button></p>