如何更改特定类名的所有类名元素 [英] How to change all classname elements of specific classname

查看:31
本文介绍了如何更改特定类名的所有类名元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更改特定类名的所有类名元素?

我的意思是,假设我有 3 个带有MyClass"类的 div,我想将它们的类名更改为notMyClass";在 JavaScript 中,怎么做?

<div class="MyClass">

<div class="MyClass">

<!--TO--><div class="notMyClass">

<div class="notMyClass">

<div class="notMyClass">

我知道通过 id 调用元素很容易,但是如何通过它的类名来调用呢?

解决方案

使用 querySelectorAll,然后遍历每个元素(使用 NodeList.forEach) 并使用 classList.replace:

document.querySelectorAll('.MyClass').forEach(e => e.classList.replace('MyClass', 'notMyClass'))

.notMyClass{背景颜色:绿色;}

<div class="MyClass">A</div><div class="MyClass">B</div><div class="MyClass">C</div><!--TO--><div class="notMyClass">D</div><div class="notMyClass">E</div><div class="notMyClass">F</div>

How to change all classname elements of specific classname?

I mean, let's say I have 3 divs with classes "MyClass", and i want to change their classnames to "notMyClass" in JavaScript, how to do it?

<div class="MyClass">
</div>
<div class="MyClass">
</div>
<div class="MyClass">
</div>

<!--TO-->

<div class="notMyClass">
</div>
<div class="notMyClass">
</div>
<div class="notMyClass">
</div>

I know that it's very easy by calling element by it's id, but how to do it by it's classname?

解决方案

Select all elements with the MyClass class with querySelectorAll, then loop through each element (with NodeList.forEach) and use classList.replace:

document.querySelectorAll('.MyClass').forEach(e => e.classList.replace('MyClass', 'notMyClass'))

.notMyClass{
  background-color:green;
}

<div class="MyClass">A</div><div class="MyClass">B</div><div class="MyClass">C</div>

<!--TO-->

<div class="notMyClass">D</div><div class="notMyClass">E</div><div class="notMyClass">F</div>

这篇关于如何更改特定类名的所有类名元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆