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