ClassList.add() for multiple divs with same className - No jQuery

前端 未结 1 1913
一整个雨季
一整个雨季 2021-01-29 09:26

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

相关标签:
1条回答
  • 2021-01-29 10:20

    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.

    0 讨论(0)
提交回复
热议问题