JS batch get class naming node getElementsByClassName ()
GetElementsByClassName () is an old method, which is optimized and provided to you.
The Code is as follows:
// Obtain class naming nodes in batches
Function getElementsByClassName (className, tag, parent ){
Var parent = parent | document;
Var tag = tag | "*";
If (! (Parent = F $ (parent) {return false ;}
// Search for all matching tags
Var allTags = (tag = "*" & parent. all )? Parent. all: F $ (tag, parent );
Var classElements = [];
// Create a regular expression to determine the correctness of className
ClassName = className. replace (/\-/g ,"\\-");
Var regex = new RegExp ("(^ | \ s)" + className + "(\ s | $ )");
Var elenemts;
// Check each element
For (var I = 0; I <allTags. length; I ++ ){
Elem = allTags [I];
If (regex. test (elem. className )){
ClassElements. push (elem );
}
}
Return classElements;
};
GetElementsByClassName (className, tag, parent) accepts three parameters:
ClassName: class Name of the node to be obtained
Tag: the class label option indicates "*" All labels by default.
Parent: All content under the parent node, that is, the obtained range. The optional default value is "document"
Instance:
HTML:
<P class = "main" id = "main">
<A href = "#" class = "my"> This is the link </a>
<Span class = "my"> 1 </span>
<Span id = "sss"> 2 </span>
<Span class = "my ttt"> 3 </span>
<Span> 4 </span>
</P>
Run: getElementsByClassName ("my", "span", document. getElementById ("main "));
Alternatively, an array containing the SPAN1 and SPAN3 nodes will be obtained. "The node does not contain the tag, because the parameter must be specified as A span before extraction 』.
There are also the following examples:
GetElementsByClassName ("my") // obtain all. my nodes in the document.
GetElementsByClassName ("my", "span") // obtain the span node named. my in the document.
GetElementsByClassName ("my", "*", document. getElementById ("main") // obtain all. my named nodes under # main.