JavaScript 向元素添加类名

JavaScript 向元素添加类名

在本文中,我们将学习如何向元素添加类名属性,并通过示例了解其实现。类名属性可以由CSS和JavaScript用于对具有指定类名的元素执行特定任务。使用JavaScript添加类名可以通过多种方式进行。

使用className属性: 此属性用于向选定的元素添加类名。

语法:

// It is used to set the className property.
element.className = "newClass";

// It is used to return the className property.
element.className;

属性值:

  • newClass: 它指定了元素的类名。要应用多个类,需要用空格分隔。

返回值: 返回的是一个字符串,表示具有以空格分隔的类或类列表的元素。

示例: 这个示例使用.className属性来添加一个类名。

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript to add class name</title>
    <style>
        .addCSS {
            color: green;
            font-size: 25px;
        }
    </style>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p id="p">
        A Computer Science portal for Geeks. 
    </p>
 
    <button onclick="addClass()"> 
        AddClass 
    </button>
 
    <!-- Script to add class name -->
    <script>
        function addClass() {
            let v = document.getElementById("p");
            v.className += "addCSS";
        }
    </script>
</body>
</html>

输出:

JavaScript 向元素添加类名

使用 .add() 方法: 该方法用于向所选元素添加类名。

语法:

element.classList.add("newClass");

示例: 该示例使用 add() 方法为元素添加类名。

<!DOCTYPE html>
<html>
<head>
    <title>
        JavaScript Adding a class 
        name to the element
    </title>
 
    <style>
        .addCSS {
            background-color: green;
            color: white;
            padding: 20px;
            font-size: 25px;
        }
    </style>
</head>
 
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
 
    <p id="p"> 
        A Computer Science portal for Geeks. 
    </p>
 
    <button onclick="addClass()"> 
        AddClass 
    </button>
 
    <!-- Script to add class name -->
    <script>
        function addClass() {
            let elem = document.getElementById("p");
            elem.classList.add("addCSS");
        }
    </script>
</body>
</html>

输出:

JavaScript 向元素添加类名

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程