JavaScript css class name Operation

1.className property

This property can be assigned directly to the add / modify the class name
Cons: The new assignment will overwrite the previous value, the value on the basis of previous reservations even add can not guarantee no repeat

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Test</title>
    <style>
        .center{
            text-align: center;
        }
        .redFont{
            color:red;
        }
    </style>
</head>
<body>
    <div>我是div1</div>
    <div class="redFont">我是div2</div>
    <div class="redFont">我是div3</div>
    <div class="center">我是div4</div>
</body>
</html>
<script>
    var divs = document.querySelectorAll("div")
    // 添加类名
    divs[0].className = "redFont"
    // 移除所有类名
    divs[1].className = ""
    // 在原有基础上添加类名 非重复
    divs[2].className += " center"
    // 在原有基础上添加类名 重复
    divs[3].className += " center"
</script>

:( operating results can not automatically handle those duplicate values, if you want to remove a class, it is more trouble to a lot of logic, it is hard to deal with)

the following code above the result is the same, only listed reference

<script>
    var divs = document.querySelectorAll("div")
    // 为class属性添加类名
    divs[0].setAttribute("class","redFont")
    // 移除class属性
    divs[1].removeAttribute("class")
    // 在原有基础上添加类名 非重复
    var d2_val = divs[2].getAttribute("class") + " center"
    divs[2].setAttribute("class",d2_val)
    // 在原有基础上添加类名 重复
    var d3_val = divs[3].getAttribute("class") + " center"
    divs[3].setAttribute("class",d3_val)
</script>

2.classList property

This property returns the list of elements css class names
Note: this is the new HTML5 attributes inside the old version of the browser is not supported.
The significance of this property is to solve existing className attribute add / remove problems encountered by the new class name, class name with an array of the existing management it up, easy to remove, and add. So the direct assignment of this element is meaningless.
This property is for convenience of added / removed in the form of an array of class names, see the specific method related to the back

<body>
    <div class="center redFont">我是div</div>
</body>

<script>
    var div = document.querySelector("div")
    console.log(div.classList) //  ["center", "redFont", value: "center redFont"]
    // 直接修改classList属性语法上可以,但是没有实际意义
    div.classList = "test test2"
    console.log(div.classList) // ["test", "test2", value: "test test2"]
</script>

operation result:

<div class="test test2">我是div</div>

Guess you like

Origin www.cnblogs.com/OrochiZ-/p/11601106.html