Javascript advanced programming --- classList attributes

Source: Internet
Author: User

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.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.