A summary of three ways to set the element class in JS

Source: Internet
Author: User

One, El.setattribute (' class ', ' abc ');

<!DOCTYPE HTML> <HTML> <HEAD> <MetaCharSet= "Utf-8" /> <title>SetAttribute (' class ', ' abc ')</title> <styletype= "Text/css">. ABC{background:Red; } </style> </HEAD> <BODY> <DivID= "D1">Test Div</Div> <Script> varDiv=document.getElementById ('D1'); Div.setattribute ("class", "ABC"); </Script> </BODY> </HTML> 

IE6/7: div background color is not red
Ie8/9/10/firefox/safari/chrome/opera:div background color is red
Result: IE6/7 does not support setattribute (' class ', XXX) to set the class of the element.

Ii. el.setattribute (' className ', ' abc ')

<!DOCTYPE HTML> <HTML> <HEAD> <MetaCharSet= "Utf-8" /> <title>SetAttribute (' ClassName ', ' abc ')</title> <styletype= "Text/css">. ABC{background:Red; } </style> </HEAD> <BODY> <DivID= "D1">Test Div</Div> <Script> varDiv=document.getElementById ('D1'); Div.setattribute ("ClassName", "ABC"); </Script> </BODY> </HTML> 

IE6/7: div background color is red
Ie8/9/10/firefox/safari/chrome/opera:div background color is not red
Result: Ie8/9/10/firefox/safari/chrome/opera does not support setattribute (' className ', XXX) way to set the class of the element.
Interestingly, when using setattribute, the first argument for class and classname is exactly the opposite of Ie6/7 and Ie8/9/10/firefox/safari/chrome/opera.

Third, el.classname = ' abc ';

<!DOCTYPE HTML> <HTML> <HEAD> <MetaCharSet= "Utf-8" /> <title>El.classname = ' abc '</title> <styletype= "Text/css">. ABC{background:Red; } </style> </HEAD> <BODY> <DivID= "D1">Test Div</Div> <Script> varDiv=document.getElementById ('D1'); Div.classname= 'ABC'; </Script> </BODY> </HTML> 

Recommended use: All browsers support

A summary of three ways to set the element class in JS

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.