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));
Author by
Wojciech
Updated on November 27, 2022Comments
-
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 over 5 yearselems is a collection, not a single element.... You are looping over it, but you are not referencing the single element.
elems[i]
And yourmyJavascriptFunc
is not going to work with "this", thethis
is going to bewindow
-
-
Wojciech over 5 yearsBut how to get a data attribute only from "active" element and not from all?
-
Maheer Ali over 5 years@Wojciech You mean that there is only one
active element
inside whole document? -
Wojciech over 5 yearsYes, only one active.
-
Maheer Ali over 5 years@Wojciech Then use
querySelector('.active').dataset.headertext