Today in the work, the use of the set classname, so consult the information, summed up.
First, how to get the class attribute with native JS
1 < = "Dom ' > 2 </div>
Element JS Implementation method:
1 function$class (Domclass)2 {3 varOdiv = document.getElementsByTagName ("*");4 varAresult = [];//defines an empty array to hold the same elements as the target classname5 for(vari = 0; i<odiv.length; i++)6{//This is done by traversing all the elements in the page and comparing them with their class. If the Domclass is the same as the one we passed in, put him in the array aresult. 7 if(Odiv[i].classname = =Domclass)8 {9Aresult.push (Odiv[i]);//gets the element in the push arrayTen } One returnAresult;//returns an array of Domclass elements that have been put into the A } - } -Window.onload =function(){ theAlert ($class (' boom '). length);//get the number of these elements -Alert ($class (' boom ') [0].classname];//getting the classname of the first element of these elements is, in fact, the same classname. -}
It is simple to use this function to obtain only the var d = $class ("Dom");
The meaning of this function is:
var odiv = document.getElementsByTagName ("*");
This means getting all the DOM elements in the page
Second, JS change or add classname
1 <styletype= "Text/css">2 . Newdiv{3 Font-weight:Bold;4 }5 </style>
1 <Script>2 functionCLK () {3 varParent=document.getElementById ("Parent");4 //parent.classname = parent.classname + "Newdiv"; Add classname5 6 Parent.classname= "Newdiv"; //Change classname7 8 }9 </Script>Ten One </Head> A <Body> - <inputtype= "button"value= "click"onclick= "CLK ();"/> - <DivID= "Parent"class= "Google"> the <Div>Child</Div> - </Div> - - </Body>
Native JS gets the class attribute of the element (gets all the elements of Class) and changes or adds Calssname