Home > Web Front-end > JS Tutorial > JavaScript cross-browser method to obtain the same class node in the page_javascript skills

JavaScript cross-browser method to obtain the same class node in the page_javascript skills

WBOY
Release: 2016-05-16 16:11:27
Original
1222 people have browsed it

When developing web pages, many times we need to operate elements with the same class name, that is, elements with the same class. I took the written test yesterday and I couldn’t answer a related question:

JavaScript gets the node with class test in the page

So I collected some relevant information and listed two methods that I think are better in this article. If there are any shortcomings, I hope everyone can criticize and correct them. If you have a better method, I hope you can share it.

Solution1 Jeremy Keuth Solution

Uncle Jeremy Keuth talked about the getElementsByClass method in Chapter 3, Section 4 of the book "The Art of JavaScript DOM Programming (2nd Edition)" (English: DOM Scripting-Web Design with JavaScript and the Document Object Model). It also talks about how to apply this method in browsers that do not support this attribute (IE6, IE7 and IE8, let us despise them). The excerpt is here, with modifications in some places.

There is a new method in HTML5 DOM that allows us to access elements through the class name in the class attribute. This is: getELementsByClassName. Since the method is relatively new, it is not yet available in some DOM implementations, so be careful when using it. . Let's first take a look at what this method can do for us, and then discuss how to use this method reliably.
Similar to the getELementsByTagName method, getElementsByClassName only accepts one parameter, which is the class name:

Copy code The code is as follows:

getElementsByClassName(class)

The return value of this method is also similar to getElementsByTagName. It is an array of elements with the same class name. The following line of code returns an array containing all elements with the class name "sale":
Copy code The code is as follows:

document.getElementsByClassName("sale")

You can also use this method to find elements with multiple class names. To specify multiple class names, simply separate the class names with spaces in the string argument. For example, add the following line of code to the <script> tag: <br> <div class="codetitle"> <span><a style="CURSOR: pointer" data="71155" class="copybut" id="copybut71155" onclick="doCopy('code71155')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code71155"> <br> alert(document.getElementsByClassName("sale important").length);<br> </div> <p><strong>Full code</strong></p> <p></p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="10676" class="copybut" id="copybut10676" onclick="doCopy('code10676')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code10676"> <br> <!DOCTYPE html><br> <html> <br> <head><br> <meta charset="utf-8"> <br> <title>Shopping List</title><br> </head> <br> <body><br> <h1>What to buy</h1><br> <p title="a gentle reminder">Don't forget to buy this stuff.</p><br> <ul id="purchase"><br>                                                                                                                                                                                                                                                                                                                                       </ul><br> <script><br> alert(document.getElementsByClassName("sale important").length);<br> </script>





You will see 1 displayed in the warning box, indicating that only one element matches, because there is only one element with both "important" and "sale" class names. Note that even if the class attribute of the element is in the order of "sale important" instead of "important sale" specified in the parameter, the element will still be matched. Not only does the actual order of the class names not matter, it doesn't matter if the element also has more class names. Just like using getELementsByTagName, you can also use getElementsByClassName and getElementById in combination. If you want to know how many list items whose class name contains test are in the element with id purchase, you can first find that specific object and then call getElementsByClassName:

Copy code The code is as follows:

var shopping=document.getElementById("purchase");
var sales = shopping.getElementsByClassName("sale");

In this way, the sales array only contains elements with the "sales" class in the "purchase" list. Run the following line of code and you will see that the sales array contains two items:

Copy code The code is as follows:

alert(sales.length);

This getELementsByClassName method is very useful, but only newer browsers (Safari 3.1, Chrome, Firefox 3 and Opera 9.5 and above) support it. In order to make up for this shortcoming, DOM script programmers need to use existing DOM methods to implement their own getElementsByClassName, which is a bit like a rite of passage. In most cases, their implementation process is roughly similar to the getElementsByClassName below. This function can be applied to both old and new browsers.

Copy code The code is 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 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 of the search in the DOM tree, and the second classname is the class name to be searched. If the appropriate getElementsByClassName function already exists on the incoming node, then this new function will directly return the corresponding node list. If the getElementsByClassName function does not exist, this new function will loop through all tags and find elements with the corresponding class name.

The disadvantage of this method is that it does not work with multiple class names.

If you use this function to simulate the previous operation of obtaining the shopping list, you can write it like this:

Copy code The code is as follows:

var shopping=document.getElementById("purchase");
var sales = shopping.getElementsByClassName(shopping,"test");
console.log(sales);

So, to solve the question at the beginning of the article, the code used is as follows:

Copy code The code is as follows:




   
    Shopping List


   

What to buy


   

Don't forget to buy this stuff.


   

           
  • A thin of beans

  •        
  • Cheese

  •        
  • Milk

  •    

<script><br>     function getElementsByClassName(node,classname){<br>         if(node.getElementsByClassName){<br>             return node.getElementsByClassName(classname);<br>         }else{<br>             var results = [];<br>             var elems = node.getElementsByTagName("*");<br>             for(var i=0;i<elems.length;i ){<br>                if(elems[i].className.indexOf(classname)!=-1){<br>                    results[results.length]=elems[i];<br>                }<br>             }<br>             return results;<br>         }<br>     }<br>     var body = document.getElementsByTagName("body")[0];<br>     var sales= getElementsByClassName(body,"sales");<br>     console.log(sales);<br> </script>


Solution2 Robert Nyman方案

搜索匹配的DOM元素的方法还有很多,但真正高效的却不多,Jeremy Keuth大叔的方法有一个缺点就是不能用于多个类名,2008年,Robert Nyman在文章 The Ultimate GetElementsByClassName, Anno 2008中提供了自己的解决方案。在2005年,Robert大叔就已经给出了自己的getElementsByClassName的函数,在2008年的时候,修改了部分代码,添加了许多新的功能:

1.如果当前浏览器支持getElementsByClassName函数,则调用该原生函数;
2.如果当前浏览器支持则使用XPath;//小飞鱼:一种浏览器内置的定位XML文档的强大方式,不过浏览器支持方面不统一
3.支持多个类名的搜索,不计先后顺序;
4.返回真正的节点数组,而不是原生的一个nodelist。//小飞鱼:原生的getElementsByClassName方法返回的是一个NodeList对象,它很像数组,有length和数字索引属性,但并不是数组,不能用pop,push等数组特有的方法,Robert提供的代码中,将NodeList对象转成了数组。可以将NodeList对象转换成数组的方法:

复制代码 代码如下:

myList = Array.prototype.slice.call (myNodeList)

这是Robert大叔的方法,有些地方还不太明白,待我研究一下再来更新好了。

复制代码 代码如下:

/*
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                 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                 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                 classesToCheck.push(new RegExp("(^|\s)" classes[k] "(\s|$)"));
            }
            for(var l=0, ll=elements.length; l                 current = elements[l];
                match = false;
                for(var m=0, ml=classesToCheck.length; m                     match = classesToCheck[m].test(current.className);
                    if (!match) {
                        break;
                    }
                }
                if (match) {
                    returnElements.push(current);
                }
            }
            return returnElements;
        };
    }
    return getElementsByClassName(className, tag, elm);
};
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template