Native JS gets the class attribute of the element (gets all the elements of Class) and changes or adds Calssname

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.