如何使用Javascript为给定元素添加类?
在 JavaScript 中,有多种方法可以为元素添加类。我们可以使用.className属性或.add()方法为特定元素添加类名。
类属性可以在 CSS 中用于对具有相同类名的元素执行某些操作。
使用 className 属性
我们可以使用此属性为HTML元素添加类,而不会重置其现有类。此属性可以用来获取元素的class属性的值。
如果元素已声明一个类,并且我们必须为此元素添加一个新的类名,则应在编写类名前插入一个空格。(例如 document.getElementById("").className = " newClass");
语法
您可以像下面这样设置此属性的值:
element.className += "newClass";
其中 newClass 指定元素的类名。要应用多个类,需要用空格分隔。
以下语句返回 className 属性的值。
element.className;
此属性保存一个字符串值,表示类名或用空格分隔的类名列表。
示例 1
在下面的示例中,我们使用.className属性添加类名。
<!DOCTYPE html>
<html lang="en">
<head>
<title>class</title>
</head>
<style>
.CSS{
color: blueviolet;
font-style: italic;
background-color: rgb(227, 171, 171);
}
</style>
<body>
<button onclick="addClass()">AddClass</button>
<h3 id="heading" >Tutorialspoint easy to learn</h3>
<script>
function addClass(){
var add_class = document.getElementById("heading");
add_class.className += "CSS";
}
</script>
</body>
</html>
点击按钮(AddClass)后,标题看起来像下面的图片。
示例 2
在下面的示例中,我们也可以使用以下代码执行相同的操作,它将给出相同的输出。
<!DOCTYPE html>
<html lang="en">
<head>
<title>class</title>
</head>
<style>
.CSS{
color: blueviolet;
font-style: italic;
background-color: rgb(227, 171, 171);
}
</style>
<body>
<button onclick="addClass()">AddClass</button>
<h3 id="heading" >Tutorialspoint easy to learn</h3>
<script>
function addClass(){
var add_class = document.getElementById("heading").className = "CSS";
}
</script>
</body>
</html>
使用 add() 方法
此方法用于为首选或选定的元素添加类名。以下是此方法的语法:
Element.classList.add("newClass");
示例 1
在下面的示例中,我们使用add()方法为具有id = p1的段落元素添加类名。
<!DOCTYPE html>
<html>
<head>
<title>add class name using JavaScript</title>
<style>
.newClass {
font-size: 30px;
background-color: rgb(149, 237, 136);
color: rgb(19, 21, 19);
border: 2px solid rgb(58, 35, 35);
}
</style>
</head>
<body>
<h1>Hello Tutorialspoint :)</h1>
<p id="p1">Welcome to the tutorialspoint.com</p>
<p>Click the following button to see the effect.</p>
<button onclick="addClass()">Add Class</button>
<script>
function addClass() {
var add_class = document.getElementById("p1");
add_class.classList.add("newClass");
}
</script>
</body>
</html>
示例 2
在下面的示例中,我们向现有类添加一个新类。
<!DOCTYPE html>
<html lang="en">
<head>
<title>class</title>
</head>
<style>
.CSS {
color: blueviolet;
font-style: italic;
background-color: rgb(227, 171, 171);
}
</style>
<body>
<button onclick="addClass()">AddClass</button>
<h3 id="heading" class="head">Tutorialspoint easy to learn</h3>
<script>
function addClass() {
var add_class = (document.getElementById("heading").className = " CSS");
//add_class.className += "CSS";
}
</script>
</body>
</html>
点击按钮(Add class)之前。这里类没有改变。
点击按钮(Add Class)之后。这里类从head变为CSS。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP