Of course, these selectors are some methods of jQuery extension, so how to find elements when using native js? Let’s briefly sort it out today.
DOM defines a variety of methods for finding elements. In addition to our commonly used getElementById(), there are also getElementsByTagName() and getElementsByName(). Using these methods we can find any html element in the html document.
getElementById()
First let’s take a look at getElementById(). This method is very simple. Just pass in the id attribute value of the html tag in the parameter. That's it, since the id in the html page is unique, this method returns a single element object. For example:
span tag
<script><br> var oSpan = document.getElementById('span1'); //Find the span element <br> alert(oSpan.innerHTML); //Pop up the span tag The content of <br> </script>
getElementsByTagName()
getElementsByTagName() parameter needs to be passed in an html tag name , it returns a list of all matching elements in the HTML document. This list has some characteristics of an array, so it is also called an array-like element. When we want to operate on a specific element, we can use array index or item() to achieve it, for example:
<script><br> var oDiv = document.getElementsByTagName('div'); //Find all div elements and return a list of elements <br> /* Operation specific Element*/<br> alert(oDiv[0].innerHTML) //Pop up the content in the first div<br> alert(oDiv.item(1).innerHTML) //Pop up the content in the second div<br> </script>
Of course we can also loop through the nodes through the length attribute:
<script><br> var oDiv = document.getElementsByTagName('div'); <br> for(var i = 0; i < oDiv. length; i ){<br> //do something<br> }<br> </script>
getElementsByName()
getElementsByName() is often used to find form elements. The name attribute value of the html tag is passed in as the parameter. Since the name value of multiple html tags in the document may be the same (such as radio buttons), this method also returns a list of elements. The specific operation method is similar to getElementsByTagName(), so I won’t go into details here.