JavaScript to get the same class node on the page in a browser _javascript tips

Source: Internet
Author: User

Web page development, in many cases we need to manipulate the same class name elements, that is, class the same element. Yesterday to participate in the written exam, there is a related topic did not answer:

JavaScript Gets the node with class test in the page

Then collected a number of relevant data, in this article listed in the two I think the better method, deficiencies, but also hope that everyone criticized. If we have a better way, I hope we can share it.

Solution1 Jeremy Keuth Program

Jeremy Keuth in "JavaScript DOM Programming Art" (2nd edition) (English: Dom Scripting-web design with JavaScript and the document Object Model) Chapter III of the book The fourth section describes the method of Getelementsbyclass, and describes how to apply this method in browsers that do not support the attribute (IE6,IE7 and IE8, let us despise them), where the excerpt is modified in individual places.

A new method in the HTML5 Dom lets us access the element through the class name in the Class attribute, which is: Getelementsbyclassname, because the method is newer, some of the DOM implementations are not, so be careful when you use it. Let's take a look at what this method can do for us and then discuss how to use the method reliably.
Similar to the getElementsByTagName method, Getelementsbyclassname accepts only one parameter, the class name:

Copy Code code as follows:

Getelementsbyclassname (Class)

The return value of this method, also similar to getElementsByTagName, is an array of elements with the same class name, and the following line of code returns an array containing all the elements of the class named "Sale":
Copy Code code as follows:

Document.getelementsbyclassname ("Sale")

You can also use this method to find elements with multiple class names. To specify more than one class name, simply separate the class name with a space in the string argument. For example, add the following line of code to the <script> tab:
Copy Code code as follows:

Alert (Document.getelementsbyclassname ("sale Important"). length);

Complete code

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>shopping list</title>
<body>
<p title= "A gentle reminder" >don ' t forget to buy this stuff.</p>
<ul id= "Purchase" >
<li>a Thin of beans</li>
<li class= "Sale" >Cheese</li>
<li class= "Sale Important" >Milk</li>
</ul>
<script>
Alert (Document.getelementsbyclassname ("sale Important"). length);
</script>
</body>

You will see that the warning box shows 1, indicating that only one element matches, because only one element has both the "important" and "sale" class names. Note that even in the class attribute of an element, the order of the class name is "sale important" rather than "important sale" specified in the parameter, and the element is also matched. Not only is the actual order of the class name unimportant, it does not matter if the element has more class names. As with getElementsByTagName, Getelementsbyclassname and getElementById can also be used in combination. If you want to know how many of the class names in the element with ID purchase contain the list item for test, you can first locate the particular object and then call Getelementsbyclassname:

Copy Code code as follows:

var Shopping=document.getelementbyid ("Purchase");
var sales = shopping.getelementsbyclassname ("Sale");

In this way, the sales array contains only elements with the "Sales" class in the "Purchase" list, and you will see that the sales array contains two items if you run the following line of code:

Copy Code code as follows:

alert (sales.length);

This getelementsbyclassname method is very useful, but only newer browsers (Safari 3.1,chorme,firefox 3 and Opera 9.5) support it. To make up for this, Dom scripting programmers need to use the existing Dom method to implement their own getelementsbyclassname, a bit like a rite of mitzvah. In most cases, their implementation is roughly similar to the following getelementsbyclassname, which can be applied to new and old browsers.

Copy Code code as follows:

function Getelementsbyclassname (node,classname) {
    if (node.getelementsbyclassname) {
         return Node.getelementsbyclassname (classname);
   }else{
        var results = [];
        var elems = node.getelementsbytagname ("*");
        for (var i=0;i<elems.length;i++) {
             if (Elems[i].classname.indexof (className)!=-1) {
                 Results[results.length]=elems[i];
           }
       }
    return results;
   }
}

This getelementsbyclassname function accepts two parameters. The first node represents the starting point for the search in the DOM tree, and the second classname is the name of the class to search for. If the appropriate Getelementsbyclassname function is already present on the incoming node, the new function directly returns the corresponding node list. If the Getelementsbyclassname function does not exist, the new function loops through all the tags to find the element with the corresponding class name.

The disadvantage of this approach is that it does not apply to multiple class names.

If you use this function to simulate the previous action to get a shopping list, you can write this:

Copy Code code as follows:

var Shopping=document.getelementbyid ("Purchase");
var sales = Shopping.getelementsbyclassname (shopping, "test");
Console.log (sales);

Therefore, to solve the problem at the beginning of the article, the code used is as follows:

Copy Code code as follows:

<! DOCTYPE html>
<meta charset= "Utf-8" >
<title>shopping list</title>
<body>
<p title= "A gentle reminder" >don ' t forget to buy this stuff.</p>
<ul id= "Purchase" >
<li>a Thin of beans</li>
<li class= "Sale" >Cheese</li>
<li class= "Sale Important" >Milk</li>
</ul>
<script>
function Getelementsbyclassname (node,classname) {
if (node.getelementsbyclassname) {
return Node.getelementsbyclassname (classname);
}else{
var results = [];
var elems = node.getelementsbytagname ("*");
for (Var i=0;i<elems.length;i++) {
if (Elems[i].classname.indexof (className)!=-1) {
Results[results.length]=elems[i];
}
}
return results;
}
}
var BODY = document.getElementsByTagName ("body") [0];
var sales= getelementsbyclassname (Body, "sales");
Console.log (sales);
</script>
</body>

Solution2 Robert Nyman Program

There are many ways to search for matching DOM elements, but the real efficiency is not much, Jeremy Keuth's approach has a disadvantage is not used in multiple class names, 2008, Robert Nyman in the article The ultimate Getelementsbyclassname, Anno 2008 offers its own solution. In 2005, Uncle Robert had given his own getelementsbyclassname function, in 2008, modified some of the code, adding a lot of new features:

1. Call the native function if the current browser supports the Getelementsbyclassname function;
2. Use xpath;//small flying fish if current browser support: A powerful way to locate XML documents built into browsers, but not consistent with browser support
3. Support multiple class name search, regardless of order;
4. Returns a true array of nodes, rather than a native nodelist. Little flying Fish: The native Getelementsbyclassname method returns a NodeList object that is very much like an array, has length and numeric indexed properties, but is not an array, and cannot be used in the same way as an array of Pop,push, which Robert provides , the NodeList object is converted to an array. You can convert a NodeList object to an array of methods:

Copy Code code as follows:

MyList = Array.prototype.slice.call (mynodelist)

This is the way Uncle Robert, in some places do not quite understand, until I study the update.

Copy Code code as follows:

/*
Developed by Robert Nyman, http://www.robertnyman.com
code/licensing:http://code.google.com/p/getelementsbyclassname/
*/
var getelementsbyclassname = function (className, tag, elm) {
if (document.getelementsbyclassname) {
Getelementsbyclassname = function (className, tag, elm) {
Elm = Elm | | Document
var elements = Elm.getelementsbyclassname (ClassName),
NodeName = (tag)? New RegExp ("\\b" + tag + "\\b", "I"): null,
Returnelements = [],
Current
For (Var i=0, il=elements.length i<il; i+=1) {
current = Elements[i];
if (!nodename | | nodename.test (current.nodename)) {
Returnelements.push (current);
}
}
return returnelements;
};
}
else if (document.evaluate) {
Getelementsbyclassname = function (className, tag, elm) {
Tag = Tag | | "*";
Elm = Elm | | Document
var classes = Classname.split (""),
Classestocheck = "",
Xhtmlnamespace = "http://www.w3.org/1999/xhtml",
Namespaceresolver = (Document.documentElement.namespaceURI = = = Xhtmlnamespace)? Xhtmlnamespace:null,
Returnelements = [],
Elements
Node
For (Var j=0, jl=classes.length j<jl; j+=1) {
Classestocheck + = "[Contains (Concat (', @class, '), '" + classes[j] + ")]";
}
try {
elements = Document.evaluate (".//" + tag + Classestocheck, Elm, namespaceresolver, 0, NULL);
}
catch (e) {
elements = Document.evaluate (".//" + tag + classestocheck, elm, NULL, 0, NULL);
}
while (node = Elements.iteratenext ())) {
Returnelements.push (node);
}
return returnelements;
};
}
else {
Getelementsbyclassname = function (className, tag, elm) {
Tag = Tag | | "*";
Elm = Elm | | Document
var classes = Classname.split (""),
Classestocheck = [],
elements = (Tag = = "*" && elm.all)? Elm.all:elm.getElementsByTagName (TAG),
Current
Returnelements = [],
Match
For (Var k=0, kl=classes.length k<kl; k+=1) {
Classestocheck.push (New RegExp ("(^|\\s)" + Classes[k] + "(\\s|$)"));
}
For (Var l=0, ll=elements.length l<ll; l+=1) {
current = Elements[l];
Match = false;
For (Var m=0, ml=classestocheck.length m<ml; m+=1) {
Match = Classestocheck[m].test (current.classname);
if (!match) {
Break
}
}
if (match) {
Returnelements.push (current);
}
}
return returnelements;
};
}
Return Getelementsbyclassname (className, tag, elm);
};

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.