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


当前回答

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元素的类名

其他回答

对于IE v6-9(其中不支持classList,并且不希望使用polyfills):

var elem = document.getElementById('some-id');

// don't forget the extra space before the class name
var classList = elem.getAttribute('class') + ' other-class-name';

elem.setAttribute('class', classList);

Try:

element.className='second'

函数更改(box){box.className='second'}.first{width:70px;height:70px,background:#ff0}.second{width:150px;height:150px,background:#f00;transition:1s}<div onclick=“change(this)”class=“first”>单击我</div>

这对我很有用:

function setCSS(eleID) {
    var currTabElem = document.getElementById(eleID);

    currTabElem.setAttribute("class", "some_class_name");
    currTabElem.setAttribute("className", "some_class_name");
}

选项。

这里有一个小样式与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")


哇,奇怪这里有这么多过分的答案。。。

<div class="firstClass" onclick="this.className='secondClass'">