最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught TypeError: Cannot read property 'contains' of undefined - Stack Overflow

programmeradmin0浏览0评论

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 your myJavascriptFunc is not going to work with "this", the this is going to be window – epascarello Commented Mar 20, 2019 at 18:00
Add a ment  | 

1 Answer 1

Reset to default 5

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));
发布评论

评论列表(0)

  1. 暂无评论