Struggling with classList.add and getElementsByClassName [duplicate]

和自甴很熟 提交于 2019-12-01 10:35:39

.getElementsByClassName() returns an HTMLCollection (array of objects) that must be iterated.

The code below will accomplish what you're after.

// Get desired elements
var element = document.getElementsByClassName('input-fieldset');

// Iterate through the retrieved elements and add the necessary class names.
for(var i = 0; i < element.length; i++)
{
    element[i].classList.add('input-fieldset-awesome');
    console.log(element[i].className);
}

Here's a working fiddle to play with.

document.getElementsByClassName returns an array-like object of all child elements which have all of the given class names.

In your case you should modify your code like this.

var element = document.getElementsByClassName('input-fieldset')[0];
element.classList.add(' input-fieldset-awesome');

or

var elements = document.getElementsByClassName('input-fieldset');
for (var i = 0; i>elements.length; i++) {
   elements[i].classList.add('input-fieldset-awesome');
}

getElementsByClassName returns a HTMLCollection which doesn't have classList property, you should iterate through the collection.

[].slice.call(document.getElementsByClassName('input-fieldset'))
  .forEach(function(elem) {
      elem.classList.add('cls');
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!