Trying to add a class to an element with a specific data attribute.
The element is: <a data-type="foo">Linkypoo</a>
I am trying to target like so:
document.querySelectorAll('[data-type="foo"]').classList.add('Booya');
but I am getting the error:
Uncaught TypeError: Cannot read property 'add' of undefined
Could someone point me in the right direction. Not sure how to do this with vanilla js.
Thank you :)
querySelectorAll
returns an Element-Collection, to access the first element use querySelectorAll(...)[0]
If you want to apply it to all Elements you can loop through them like in the Example below:
var elements = document.querySelectorAll('[data-type="foo"]')
for (var i = 0; i < elements.length; ++i) {
elements[i].classList.add('Booya');
}
.Booya {
color: red;
}
<a data-type="foo">Linkypoo 1</a>
<a data-type="foo">Linkypoo 2</a>
<a data-type="foo">Linkypoo 3</a>
<a data-type="foo">Linkypoo 4</a>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments