Search code examples
javascriptgetattribute

Uncaught TypeError: Cannot read property 'contains' of undefined


Hi i like to loop trough all "slide" items that contains a class active and take their "data-headertext" attribute. What am i doing wrong?

<div class="slide active"></div>

    var elems = document.getElementsByClassName('slide');

    for (var i = 0, len = elems.length; i < len; i++) {                
        if (elems.classList.contains("active")) {
          myJavascriptFunc
          }
        }

       function myJavascriptFunc() {
         alert(this.getAttribute('data-headertext'));
       }

Solution

  • elems in your code is a Node list which doesnot have property classList. You should access classList of element inside elems

    if (elems[i].classList.contains("active"))
    

    Simpler Way:

    And also can do that using querySelectorAll() giving it multiple classes and loop using forEach()

    const elems = document.querySelectorAll('.slide.active')
    elems.forEach(a => console.log(a.getAttribute('data-headertext')))
    

    In this case you want to get the data attributes. So better to use HTMLElement.dataset `

    const elems = document.querySelectorAll('.slide.active')
    elems.forEach(a => console.log(a.dataset.headertext));