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'));
}
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'));
}
Share
Improve this question
asked Mar 20, 2019 at 17:59
WojciechWojciech
1031 gold badge4 silver badges12 bronze badges
1
-
5
elems 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
– epascarello Commented Mar 20, 2019 at 18:00
1 Answer
Reset to default 5elems
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));