javaScript Simple Implementation of Adding Multiple class to Elements
- 2021-07-04 18:10:17
- OfStack
javaScript Simple Implementation of Adding Multiple class to Elements
<html>
<head>
<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 the className
var odiv=document.getElementById('div1');
odiv.className= div3
// So we will get class ="div3" Will directly put div2 The style is overwritten ;
[2] Assign a value to the className
var odiv=document.getElementById('div1');
odiv.className+=" "+div3 // Need a gap between styles and styles So add an empty string to separate it
// So that you can get class="div2 div3" It can be added normally, but when we add a style, we have to consider whether there is a style with the same name before it. If we add it, it will become a burden For example class="div2 div3 div3";
[3] Detect whether there is the same style before the original style
var odiv=document.getElementById('div1');
function hasClass(element,csName){
element.className.match(RegExp('(\\s|^)'+csName+'(\\s|$)')); // Use regularity to detect whether there are identical styles
}
[4] In [3] On the basis of, we can judge to add styles to elements
var odiv=document.getElementById('div1');
function hasClass(element,csName){
return element.className.match(RegExp('(\\s|^)'+csName+'(\\s|$)')); // Use regularity to detect whether there are identical styles
}
function addClass(element,csName){
if(!hasClass(element,csName)){
element.className+=' '+csName;
}
addClass(odiv,'div3');
// This gives you the flexibility to add styles to elements ;
"Element Delete Specified Style"
// The same judgment is made first, and then the deletion is carried out
var odiv=document.getElementById('div1');
function hasClass(element,csName){
return element.className.match(RegExp('(\\s|^)'+csName+'(\\s|$)')); // Use regularity to detect whether there are identical styles
}
function deleteClass(element,csName){
if(!hasClass(element,csName)){
element.className.replace(RegExp('(\\s|^)'+csName+'(\\s|$)'),' '); // Use regularity to capture the name of the style to be deleted, and then replace it with 1 Blank string, which is equivalent to deleting
}
deleteClass(odiv,div3);
}
</script>
</head>
<body>
<div id="div1" class='div2'> Test </div>
</body>
</html>