Vanilla JavaScript向元素添加类 [英] Vanilla JavaScript adding classes to elements

查看:55
本文介绍了Vanilla JavaScript向元素添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用纯JS向某些元素添加类,并且熟悉选择带有ID的元素,但是当我尝试使用getElementsByClassName时,我的代码中断了.是否无法通过类名称获取元素并添加新的类?

I would like to use pure JS to add classes to some elements and am familiar with selecting the element with an ID, but when I've tried to use getElementsByClassName, my code breaks. Is it not possible to get elements by class name and add a new class?

我知道以下代码可以工作,但是再次想通过className定位元素.

I know the following code works, but, again, would like to target the element by className.

document.getElementById("id-name").classList.add("new-class");

推荐答案

您可以使用querySelectorAll选择包含类的每个元素,然后在所有元素上添加新类:

you can use querySelectorAll to select every element containing your class, and then, add your new class on all of them :

document.querySelectorAll('.class-name')
        .forEach(element => element.classList.add('new-class'))

这篇关于Vanilla JavaScript向元素添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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