Earlier, JavaScript was not very convenient to process, as it was necessary to first obtain the class attribute and then process the string. Now 1. classList attributeFirst look at the following code: <ul class="nav"> <li class="active">Column 1</li> <li>Column 2</li> <li>Column 3</li> </ul> <script type="text/javascript"> // Get the current li element let activeLi = document.querySelector(".active"); // Print classList attribute console.log(activeLi.classList) // Console output: // DOMTokenList ['active', value: 'active'] </script> Console view effect: classList attribute type:
2. Practical Application In practice, column switching is a very common application. Continuing with the above example, when clicking a column, move <ul class="nav"> <li class="item active">Column 1</li> <li class="item">Column 2</li> <li class="item">Column 3</li> </ul> <script type="text/javascript"> let currentElement = document.querySelector(".nav").firstElementChild; // Traverse the li elements and set the click event while (currentElement) { currentElement.onclick = function() { // Remove the active li document.querySelector(".active").classList.remove("active"); // The current li class adds active this.classList.add("active"); } currentElement = currentElement.nextElementSibling; } </script> This makes it very convenient to implement without affecting other class names. This is the end of this article about the detailed explanation of how to use the new method of You may also be interested in:
|
<<: Detailed explanation of some commonly used font-size font units and line-height in CSS
>>: The spacing between multiple divs with inline-block is different from the programming method
I. Introduction 1: SSL Certificate My domain name...
This article example shares the specific code of ...
Table of contents Overview Button-level permissio...
html, address,blockquote,body, dd, div,dl, dt, fie...
Through JavaScript, we can prevent hyperlinks fro...
Table of Contents Introduction Synchronous Asynch...
1. Compile and install ovs from source code: Inst...
Maybe I started to think wrongly, and my descript...
Some MySQL tables may contain duplicate records. ...
They are all web page templates from the foreign ...
The reason for writing this article is that I wan...
In general applications, we use timestamp, dateti...
React Hooks is a new feature introduced in React ...
W3C recently released two standards, namely "...
Table of contents Preface Prepare Implementation ...