javascript 挣扎于 classList.add 和 getElementsByClassName

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24219702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 02:23:14  来源:igfitidea点击:

Struggling with classList.add and getElementsByClassName

javascriptgetelementsbyclassname

提问by aproskam

I'm trying to add a extra class to some elements with a specific class(input-fieldset).

我正在尝试为具有特定类(输入字段集)的某些元素添加一个额外的类。

<fieldset id="pay" class="input-fieldset"></fieldset>
<fieldset id="address" class="input-fieldset"></fieldset>

So I did some searches and found this:

所以我做了一些搜索,发现了这个:

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

I'm trying to add the class input-fieldset-awesome.

我正在尝试添加类 input-fieldset-awesome。

But it doesn't work, I get the error:

但它不起作用,我收到错误消息:

Uncaught TypeError: Cannot read property 'add' of undefined(anonymous function)

未捕获的类型错误:无法读取未定义的属性“添加”(匿名函数)

What am I doing wrong?

我究竟做错了什么?

回答by James Hill

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

.getElementsByClassName()返回一个必须迭代的HTMLCollection(对象数组)。

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.

这是一个可以玩的工作小提琴

回答by undefined

getElementsByClassNamereturns a HTMLCollectionwhich doesn't have classListproperty, you should iterate through the collection.

getElementsByClassName返回一个HTMLCollection没有classList属性的,你应该遍历集合。

[].slice.call(document.getElementsByClassName('input-fieldset'))
  .forEach(function(elem) {
      elem.classList.add('cls');
  });

回答by neformal

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

document.getElementsByClassName返回具有所有给定类名的所有子元素的类数组对象。

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');
}