Summary of common methods for retrieving elements in JavaScript

  • 2020-05-10 17:44:10
  • OfStack

There are three common ways to get elements, namely, by the element ID, by the tag name, and by the class name.

getElementById

DOM provides a method called getElementById that returns a node object corresponding to its id property. Use case sensitivity.

It is a function specific to the document object through which the method can only be called. The methods used are as follows:


document.getElementById('demo') //demo It's corresponding to the elements ID

This method is compatible with major browsers, including IE6+, and can be used boldly.

getElementsByTagName

This method returns an array of objects (HTMLCollection collection, to be exact, which is not really an array), each of which corresponds to an element in the document with a given label. Similar to getElementById, this method also provides only one parameter, and its parameter is the name of the specified tag. The sample code is as follows:


document.getElementsByTagname('li')  //li It's the name of the tag

It is important to note that this method can be called by ordinary elements as well as by document objects. Here's an example:


var demo = document.getElementById('demo');
var lis = demo.getElementsByTagname('li');    

Again, this approach is compatible with major browsers, including IE6+, and is a bold one to use.

getElementsByClassName

In addition to getting elements by specifying tags, DOM also provides the getElementsByClassName method to get elements with a specified class name. However, because this method is relatively new, older browsers, such as IE6, do not support it. However, we can make up for this with hack. The method is invoked as follows:


document.getElementsByClassName('demo')    //demo Specified for the element class The name

Like getElementsByTagname1, this method can be called by ordinary elements as well as by document objects.

For older browsers, such as IE6 and 7, we can do this by hack:


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;
        }
    }  

expand

If you not only satisfy the above element selection method, like JQuery1, you can get elements through the selector, the implementation method is similar to getElementsByClassName above, if you are interested, you can implement a set of selector. However, I think the above three methods combined with the event bubble, is enough, after all, these three performance is excellent.

That's all for this article, and I hope it will be helpful.


Related articles: