Javascript advanced programming --- classList attributes
1. Traditional methods:
You must use the className attribute to add, delete, and replace Class names. For example:
...
There are three class names in this div. To delete one class name from the class name, you need to split the three classes and then process them separately. The process is as follows:
<Script type = "text/javascript"> var className = div. className. split (/\ s +/); // find the class name var pos =-1, I, len; for (var I = 0; I <className. length; I ++) {if (className [I] = "user") {pos = I; break ;}; className. splice (I, 1); div. className = className. join (""); // re-assemble the remaining class names </script>
The above is a traditional method.
2. The new method classList () in html5 can completely get rid of the className attribute.
The specific use cases are as follows:
classList Example Hello world! This demo works in Firefox 3.6 and Chrome 8.
<script type="text/javascript"> function addClass(){ var myDiv = document.getElementById("myDiv"); myDiv.classList.add("highlight"); } function removeClass(){ var myDiv = document.getElementById("myDiv"); myDiv.classList.remove("highlight"); } function toggleClass(){ var myDiv = document.getElementById("myDiv"); myDiv.classList.toggle("highlight"); } function containsClass(){ var myDiv = document.getElementById("myDiv"); alert(myDiv.classList.contains("highlight")); } </script>
Note: currently, the classList attribute is only supported by FireFox3.6 + and Chrome.