I have a number of divs with the same className
(.example). I\'m attempting to add classes to the classList of each of them using vanilla JavaScrip
You need to loop through the elements using querySelectorAll()
and not querySelector()
to add classes and there's no if
you need to use:
// Select all the elements with example class.
var examples = document.querySelectorAll('.example');
// Loop through the elements.
for (var i = 0; i < examples.length; i++) {
// Add the class margin to the individual elements.
examples[i].classList.add('margin');
}
<div class="example">content</div>
<div class="example">content</div>
<div class="example">content</div>
The code above is well commented. Let me know if you have any questions.