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'));
       }
1

1 Answer

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));
4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi

Maya Lin-Takahashi

Consumer Tech & Gadget Reviewer

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.

Share this article
Twitter Facebook Pinterest