Setting, getting, and removing data attributes vanilla javascript 1

Setting, getting, and removing data attributes vanilla javascript

// setting data-foo
var el = document.querySelector('div');
el.setAttribute('data-foo', 'Hello World!');

// getting data-foo
var el = document.querySelector('img');
console.log(el.getAttribute('data-foo'))

// removing data-foo
el.removeAttribute('data-foo');

Here is what the above code is Doing:
1. We’re selecting the first div element on the page and setting a data-foo attribute to it.
2. We’re selecting the first img element on the page and getting the value of its data-foo attribute.
3. We’re removing the data-foo attribute from the img element.

Similar Posts