与classList.add和getElementsByClassName一起苦苦挣扎 [英] Struggling with classList.add and getElementsByClassName

查看:143
本文介绍了与classList.add和getElementsByClassName一起苦苦挣扎的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为具有特定类(input-fieldset)的某些元素添加额外的类。

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

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

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

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

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


未捕获的TypeError:无法读取属性'add '未定义(匿名函数)

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

我做错了什么?

推荐答案

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

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

这是一个可以玩的小提琴

这篇关于与classList.add和getElementsByClassName一起苦苦挣扎的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆