In-depth understanding of the JavaScript Selector API series The second article--getelementsbyclassname

Source: Internet
Author: User
Tags tag name

xTable of Contents [1] using [2]classlist [3] to extend the preceding words

Since there are getElementById () and getElementsByTagName () methods, why is there no getelementsbyclassname ()? The id attribute, tag name, and class attribute have no merit or disadvantage. Finally, HTML5 new Getelementsbyclassname () method, due to the widespread use of the class name in the CSS layout, the method just hit the pain point, so that the selection of elements through the class name is no longer troublesome, become the most welcome method. Next, this article will describe the method in detail

Use

The class property value of an HTML element is a space-delimited list that can be empty or contain multiple identifiers. Class is a reserved word in JavaScript, so use the ClassName property to save the value of the class property of the HTML

The Getelementsbyclassname () method receives a parameter, a string containing one or more class names, that returns a class array Object nodelist with all the elements of the specified class. When multiple class names are passed in, the order of the class names is not important. Similar to getElementsByTagName (), this method can be used for both HTML document objects and element object

Note ie8-Browser does not support

<ul id= "List" >    <li class= "a ab C" >1</li>    <li class= "a" >2</li>    <li class = "AC" >3</li>    <li class= "a b C" >4</li>    <li class= "a B" >5</li></ul> <script>// class name exists in a established Array.prototype.forEach.call (List.getelementsbyclassname (' a '),  function(item,index,arr) {    = ' bold ';}); // only A and C are present in the class name. Array.prototype.forEach.call (List.getelementsbyclassname (' A C '),function(item,index,arr) {    = ' red ';}); </script>

Classlist Property

When you manipulate the class name, you need to add, remove, and replace the class name through the ClassName property. Because classname is a string, you must set the value of the entire string every time, even if only part of the string is modified. To remove a class name from a classname string, you need to take the class name apart, delete the unwanted one, and then re-spell a new string

HTML5 adds the Classlist property for all elements, which is an instance of the new collection type Domtokenlist, which has a length property that represents how many elements it contains, and the item () method that is used to get each element. You can also use the square bracket method

Note ie9-Browser does not support

<div id= "Test" class= "a b C" ></div><script>Console.log (test.classlist); // ["A", "B", "C", Value: "A b C"]Console.log (test.classlist[0]); // aConsole.log (Test.classList.item (1)); // b</script>

In addition, this new type defines the following methods:

Add (value)              adds the given string value to the list, and if the value already exists, do not add contains (value) to        indicate whether the given value exists in the list, or return True if it exists, otherwise return Falseremove (value)          removes the given string from the list toggle (value)          if the given value already exists in the list, delete it, or add it if there is no given value in the list

With the Classlist attribute, the classname attribute is largely useless.

<style>. Cb{color:blue;} </style><body><div id= ' Test ' > Test text </div><button id= "btn1" onclick = "Test.classList.add (' CB ') ">add</button><button id=" btn2 "onclick =" test.classList.contains (' CB ')? Alert (True): Alert (False) " >contains</button><button id= "btn3" onclick = "test.classList.remove (' CB ')" >remove</button> <button id= "btn4" onclick = "test.classList.toggle (' CB ')" >toggle</button></body>

Extended

"1" because the native Getelementsbyclassname () method is incompatible with the Ie8-browser, and the method can only match the list of class names in the parameter exactly. So there are the following extensions

Extended function Getelementsbyclassname (), with richer functionality. If the parameter class name list is separated by a space, then the match is made, that is, only the class names in the element contain all the class names in the parameter class name list to match successfully, or if the parameter class name list is delimited by commas, or if the class names in the element contain one of the types in the parameter class list, even if the match succeeds

Array.prototype.noRepeat =function(){    varresult = [];  for(vari = 0; I < This. length; i++){        if(Result.indexof ( This[i]) = =-1) {Result.push ( This[i]); }    }    returnresult;} Array.prototype.inArray=function(value) { for(vari = 0; I < This. length; i++){        if( This[i] = = =value) {            return true; }    }    return false;}functionGetelementsbyclassname (parentobj,classstr) {varresult = []; //get all child elements under Parentobj    varOBJS = Parentobj.getelementsbytagname (' * ')); //condition One: If Classstr is separated by a space, it means that the class must be satisfied at the same time to be valid    varTARGETARR1 = Classstr.trim (). Split (/\s+/). Norepeat (); //condition Two: If Classstr is separated by commas, it means that the class is valid only if one satisfies    varTARGETARR2 = Classstr.trim (). Split (/\s*,\s*/). Norepeat (); //only one class or a test of condition one    if(Classstr.indexof (', ') = =-1) {label: for(vari = 0; i < objs.length; i++){            //gets the class name of each child element, converts it to an array and then goes back            vararr = Objs[i].classname.trim (). Split (/\s+/). Norepeat (); //Enter the loop to test if the condition is met             for(varj = 0; J < Targetarr1.length; J + +){                //if an item in condition one does not exist in the ARR array, the child element is skipped                if(!Arr.inarray (Targetarr1[j])) {                    Continuelabel; }            }            //Place the child element object that matches the condition one in the result arrayResult.push (Objs[i]); }        //returns an array of results        returnresult; //conduct condition two test}Else{label: for(vari = 0; i < objs.length; i++){                //gets the class name of each child element, converts it to an array and then goes back                varArr =objs[i].classname.trim (). Split (/\s+/). Norepeat (); //Enter the loop, test whether the condition is met two                 for(varj = 0; J < Targetarr2.length; J + +){                    //as long as an item in the condition two exists in the ARR array, it conforms to the                    if(Arr.inarray (Targetarr2[j])) {//Place sub-element objects that match condition two in the result arrayResult.push (Objs[i]); //then go to the next sub-element test                        Continuelabel; }                }               }        //returns an array of results        returnresult; }}
<ul id= "List" > <li class= "a ab C" >1</li> <li class= "a" >2</li> <li class= "AC" > 3</li> <li class= "a b C" >4</li> <li class= "a B" >5</li></ul><script>//existence of a in class name establishedGetelementsbyclassname (list, ' a '). ForEach (function(Item,index,arr) {item.style.fontWeight= ' Bold ';});//only A and C are present in the class name.Getelementsbyclassname (list, ' a C '). ForEach (function(Item,index,arr) {Item.style.color= ' Red ';});//established as long as B or C exists in the class nameGetelementsbyclassname (list, ' B,c '). ForEach (function(Item,index,arr) {Item.style.backgroundColor= ' Pink ';});</script>

"2" because the ie9-browser does not support the Classlist property, there is no support for the four methods of Add (), contains (), remove (), and toggle (), and the following are the four methods of compatibility.

Because the indexof () and trim () methods are ES5 new methods and are not supported in the low version of IE, they need to be repackaged

//IndexOf method Encapsulation of arraysfunctionindexOf (arr,value,start) {//If start is not set, the default start is 0    if(Arguments.length = = 2) {Start= 0; }    //if the IndexOf method exists in the array, the native IndexOf method is used    if(arr.indexof) {returnArr.indexof (Value,start); }     for(vari = start; i < arr.length; i++){        if(Arr[i] = = =value) {            returni; }    }    return-1;}//Array de-weight method encapsulationfunctionNorepeat (arr) {varresult = [];  for(vari = 0; i < arr.length; i++){        if(IndexOf (result,arr[i]) = =-1) {Result.push (arr[i]); }    }    returnresult;}//Inarray Method EncapsulationfunctionInArray (arr,value) { for(vari = 0; i < arr.length; i++){        if(Arr[i] = = =value) {            return true; }    }    return false;}//Remove the whitespace function encapsulationfunctionTrim (arr) {varresult = Arr.replace (/^\s+|\s+$/g, "); returnresult;}

1. Add function Encapsulation

function addclass (obj,classstr) {    var array = norepeat (Trim (obj.classname). Split (' \s+ '));     if (! InArray (ARRAY,CLASSSTR)) {        Array.push (CLASSSTR);    }     = Array.join (");     return obj;}

2. Contains function encapsulation

function Containsclass (obj,classstr) {    var array = norepeat (Trim (obj.classname). Split (' \s+ '));     if (InArray (array,classstr)) {        returntrue;    }     return false ;}

3. Remove function Encapsulation

function Removeclass (obj,classstr) {    var array = norepeat (Trim (obj.classname). Split (' \s+ '));     var index = indexOf (array,classstr);     if (Index! =-1) {        array.splice (index,1)        ; = Array.join (");    }     return obj;}

4. Toggle Function Encapsulation

function Toggleclass (obj,classstr) {    var array = norepeat (Trim (obj.classname). Split (' \s+ '));     if (InArray (array,classstr)) {        removeclass (OBJ,CLASSSTR);    } Else {        addclass (OBJ,CLASSSTR);    }}
<style>. CB{Color:Blue;}</style><DivID= "Test">Test text</Div><ButtonID= "BTN1"onclick= "addclass (test, ' CB ')">Add</Button><ButtonID= "BTN2"onclick= "Containsclass (test, ' CB ')?" alert (True): Alert (false) ">Contains</Button><ButtonID= "Btn3"onclick= "removeclass (test, ' CB ')">Remove</Button><ButtonID= "Btn4"onclick= "Toggleclass (test, ' CB ')">Toggle</Button>

In-depth understanding of the JavaScript Selector API series The second article--getelementsbyclassname

Related Article

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.