Home > Article > Web Front-end > Summary of common methods of obtaining elements in JavaScript_javascript skills
There are three common ways to obtain elements, namely through element ID, through tag name and through class name.
getElementById
DOM provides a method called getElementById, which will return a node object corresponding to the id attribute. Please pay attention to case sensitivity when using it.
It is a function unique to the document object, and this method can only be called through it. The method of use is as follows:
This method is compatible with mainstream browsers, even IE6, and can be used boldly.
getElementsByTagName
This method returns an array of objects (HTMLCollection to be precise, it is not an array in the true sense), each object corresponding to an element with a given tag in the document. Similar to getElementById, this method only provides one parameter, and its parameter is the name of the specified tag. The sample code is as follows:
It should be noted that in addition to being called by the document object, this method can also be called by ordinary elements. An example is as follows:
Similarly, this method is compatible with mainstream browsers, even IE6, and can be used boldly.
getElementsByClassName
In addition to obtaining elements by specifying tags, DOM also provides the getElementsByClassName method to obtain elements with specified class names. However, because this method is relatively new, older browsers do not yet support it, such as IE6. However, we can use hacks to make up for the shortcomings of old browsers. The method is called as follows:
Same as getElementsByTagname, this method can be called by ordinary elements in addition to the document object.
For older browsers, such as IE6 and 7, we can use the following hack:
Expand
If you are not only satisfied with the above element selection methods, but also want to obtain elements through selectors like JQuery. The implementation method is similar to the getElementsByClassName above. If you are interested, you can implement a set of selectors yourself. However, I think the above three methods combined with event bubbling are enough. After all, these three methods are considered excellent in terms of performance.
The above is the entire content of this article, I hope it can be helpful to everyone.