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 used is as follows:
document.getElementById('demo') //demo是元素对应的ID
This method is compatible with mainstream browsers, even IE6+, and can be used boldly.
getElementsByTagName
This method returns an array of objects (HTMLCollection collection to be precise, it is not an array in the true sense). Each object corresponds to the object in the document. An element with the given tag. 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:
document.getElementsByTagname('li') //li是标签的名字
It should be noted that this method has In addition to being called by document objects, it can also be called by ordinary elements. Examples are as follows:
If you use native DOM, first get the tag object, id or name or other
Example:
##
<p id="targetp" >2333333</p> <script> var element = document.getElementById("targetp"); var tagname = element.tagName; alert(tagname); </script>
jQuery Get
$("#content-header").get(0).tagName
<p onclick="alert('您单击的是:'+this.tagName);">中华人民共和国</p>
var demo = document.getElementById('demo'); var lis = demo.getElementsByTagname('li');
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 of calling this method is as follows:document.getElementsByClassName('demo') //demo为元素指定的class名
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; } }
If you are not just To satisfy the above element selection methods, like JQuery, you can obtain elements through selectors. 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 excellent in terms of performance.
The above is the detailed content of Detailed examples of three methods for obtaining elements in JavaScript. For more information, please follow other related articles on the PHP Chinese website!