如何使用JavaScript更改HTML元素的类以响应onclick或任何其他事件?


当前回答

这里有一个toggleClass来切换/添加/删除元素上的类:

// If newState is provided add/remove theClass accordingly, otherwise toggle theClass
function toggleClass(elem, theClass, newState) {
    var matchRegExp = new RegExp('(?:^|\\s)' + theClass + '(?!\\S)', 'g');
    var add=(arguments.length>2 ? newState : (elem.className.match(matchRegExp) == null));

    elem.className=elem.className.replace(matchRegExp, ''); // clear all
    if (add) elem.className += ' ' + theClass;
}

参见JSFiddle。

也可以在这里看到动态创建新类的答案。

其他回答

线路

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/\bMyClass\b/','')

应该是:

document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace('/\bMyClass\b/','');

可以这样使用node.className:

document.getElementById('foo').className = 'bar';

根据PPK,这应该在Internet Explorer 5.5及更高版本中工作。


选项。

这里有一个小样式与classList的示例,让您了解您有哪些可用选项,以及如何使用classList完成您想要的操作。

样式与类别列表

style和classList之间的区别在于,使用style可以将其添加到元素的样式财产中,但classList有点控制元素的类(add、remove、toggle、contain),我将向您展示如何使用add和remove方法,因为它们是最流行的方法。


样式示例

如果要将margin-top属性添加到元素中,可以这样做:

// Get the Element
const el = document.querySelector('#element');

// Add CSS property 
el.style.margintop = "0px"
el.style.margintop = "25px" // This would add a 25px to the top of the element.

classList示例

假设我们有一个<div class=“class-a class-b”>,在本例中,我们已经向div元素添加了两个类,class-a和class-b,我们希望控制删除哪些类和添加哪些类。这就是classList变得方便的地方。

删除类-b

// Get the Element
const el = document.querySelector('#element');

// Remove class-b style from the element
el.classList.remove("class-b")

添加类-c

// Get the Element
const el = document.querySelector('#element');

// Add class-b style from the element
el.classList.add("class-c")


JavaScript中有一个属性className,用于更改HTML元素类的名称。现有的类值将替换为您在className中分配的新类值。

<!DOCTYPE html>
<html>
<head>
<title>How can I change the class of an HTML element in JavaScript?</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<h1 align="center"><i class="fa fa-home" id="icon"></i></h1><br />

<center><button id="change-class">Change Class</button></center>

<script>
var change_class = document.getElementById("change-class");
change_class.onclick = function()
{
    var icon=document.getElementById("icon");
    icon.className = "fa fa-gear";
}
</script>
</body>
</html>

Credit-如何在JavaScript中更改HTML元素的类名

classList DOM API:

添加和删除类的一种非常方便的方式是classListDOMAPI。该API允许我们选择特定DOM元素的所有类,以便使用JavaScript修改列表。例如:

const el=document.getElementById(“main”);console.log(el.classList);<div class=“content wrapper animated”id=“main”></div>

我们可以在日志中观察到,我们正在取回一个对象,它不仅包含元素的类,还包含许多辅助方法和财产。此对象继承自接口DOMTokenList,该接口在DOM中用于表示一组空格分隔的令牌(如类)。

例子:

const el=document.getElementById('container');函数addClass(){el.classList.add('newclass');}函数replaceClass(){el.classList.replace('fo','newFoo');}函数removeClass(){el.classList.remove('bar');}按钮{边距:20px;}.foo文件{颜色:红色;}.newFoo{颜色:蓝色;}.巴{背景色:粉蓝色;}.new类{边框:2px实心绿色;}<div class=“foo bar”id=“container”>“全身出汗”在natus error sit volupatim accusantium doloremque audantium,totam rem开胃酒,eaque ipsa quae ab illo inventore veritatis et准建筑风格的生活格言不明确。Nemo enim ipsam公司卷舌</div><button onclick=“addClass()”>addClass</button><button onclick=“replaceClass()”>replaceClass</button><button onclick=“removeClass()”>removeClass</button>