One, El.setattribute (' class ', ' abc ');
Copy CodeThe code is as follows:
<! DOCTYPE html>
<HTML>
<HEAD>
<meta charset= "Utf-8"/>
<title>setattribute (' class ', ' abc ') </title>
<style type= "Text/css" >
. ABC {
background:red;
}
</style>
</HEAD>
<BODY>
<div id= "D1" >test div</div>
<script>
var div = 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 ')
Copy CodeThe code is as follows:
<! DOCTYPE html>
<HTML>
<HEAD>
<meta charset= "Utf-8"/>
<title>setattribute (' ClassName ', ' abc ') </title>
<style type= "Text/css" >
. ABC {
background:red;
}
</style>
</HEAD>
<BODY>
<div id= "D1" >test div</div>
<script>
var div = 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 ';
Copy CodeThe code is as follows:
<! DOCTYPE html>
<HTML>
<HEAD>
<meta charset= "Utf-8"/>
<title>el.classname = ' abc ' </title>
<style type= "Text/css" >
. ABC {
background:red;
}
</style>
</HEAD>
<BODY>
<div id= "D1" >test div</div>
<script>
var div = document.getElementById (' D1 ');
Div.classname = ' abc ';
</script>
</BODY>
</HTML>
All browsers are supported.
A summary of three ways to set the element class in JS