Uncaught TypeError: Cannot read property 'contains' of undefined

16,258

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));
Share:
16,258
Wojciech
Author by

Wojciech

Updated on November 27, 2022

Comments

  • Wojciech
    Wojciech over 1 year

    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'));
           }
    
    • epascarello
      epascarello over 5 years
      elems is a collection, not a single element.... You are looping over it, but you are not referencing the single element. elems[i] And your myJavascriptFunc is not going to work with "this", the this is going to be window
  • Wojciech
    Wojciech over 5 years
    But how to get a data attribute only from "active" element and not from all?
  • Maheer Ali
    Maheer Ali over 5 years
    @Wojciech You mean that there is only one active element inside whole document?
  • Wojciech
    Wojciech over 5 years
    Yes, only one active.
  • Maheer Ali
    Maheer Ali over 5 years
    @Wojciech Then use querySelector('.active').dataset.headertext