<style type= "Text/css" >
. div2{
font-size:16px;
Color:orange;
}
. div3{
font-size:20px;
Color:blue;
}
<style>
<script type= "Text/javascript" >
[1] Assign the style directly to classname
var Odiv=document.getelementbyid (' Div1 ');
Odiv.classname= Div3
So we will get class = "Div3" will be directly to the DIV2 style to cover out;
[2] using additive assignment to classname
var Odiv=document.getelementbyid (' Div1 ');
odiv.classname+= "" +div3//style and style need space between, so add an empty string to separate
This can get class= "Div2 div3" can increase normally, but when we add the style we have to consider whether he has the same name before the style, if we add the words will become cumbersome such as class= "Div2 div3 div3";
[3] detect if the style previously had the same style
var Odiv=document.getelementbyid (' Div1 ');
function Hasclass (element,csname) {
Element.className.match (RegExp (' (\\s|^) ' +csname+ ' (\\s|$) ')); Use regular detection to see if you have the same style
}
[4] on the basis of [3] we can be judged to add style to the element
var Odiv=document.getelementbyid (' Div1 ');
function Hasclass (element,csname) {
Return Element.className.match (RegExp (' (\\s|^) ' +csname+ ' (\\s|$) '); Use regular detection to see if you have the same style
}
function AddClass (element,csname) {
if (!hasclass (Element,csname)) {
element.classname+= ' +csname;
}
AddClass (Odiv, ' div3 ');
This gives you the flexibility to add styles to the elements;
"element Delete specified style"
The same first judgment, in the removal
var Odiv=document.getelementbyid (' Div1 ');
function Hasclass (element,csname) {
Return Element.className.match (RegExp (' (\\s|^) ' +csname+ ' (\\s|$) '); Use regular detection to see if you have the same style
}
function Deleteclass (element,csname) {
if (!hasclass (Element,csname)) {
Element.className.replace (RegExp (' (\\s|^) ' +csname+ ' (\\s|$) '); Use the regular to capture the name of the style you want to delete, and then replace it with a blank string, which is equivalent to deleting the
}
Deleteclass (ODIV,DIV3);
}
</script>
<body>
<div id= "Div1" class= ' div2 ' > Test </div>
</body>
JavaScript adds more than one class to an element