How To Select Element In The DOM
Let us now discuss each and every method in detail.
1. getElementById() Method
getElementById() is the most popular and frequently used DOM method to select HTML elements.
To select the element the "id" of the element is passed in the argument of
getElementById() method. Example
If an element with a given id is present in the
document then it returns the element else it returns null.
getElementById() is a document method so full code to use this method is
document.getElementById(). Lets see in the example.
In the above example
innerHTML is a property of the used method, which sets value to the element.
2. getElementsByClassName() Method
getElementsByClassName() is also a method to select HTML elements. This method selects elements by its class name.
The name of the class is passed in the argument of method. Example
Since we know that a class name could be used with more than one element. So this method returns all the elements with specified class names in the form of an array. You can use those elements by its index value in the array.
3. getElementsByTagName() Method
getElementsByTagName() selects all HTML elements with the mentioned tag name.
The method returns a collection of all HTML elements with a given tag name in the form of an array.
If you want to make some change to all specific tags then it is useful.
4. getElementsByName() Method
getElementsByName() is another method to select HTML elements. This method selects elements by the name attribute.
The method returns a collection of all HTML elements in the form of an array.
5. querySelectorAll() Method
querySelectorAll() method uses CSS selector string as argument to select the element. You can select any element that can be selected by CSS using CSS selector string. Example
- selector=".class1" - will select all elements with this classname
- selector="#id1" - will select the element with this id
- selector=".class1.class2" - will select all elements having both class
- selector=".class1 .class2" - will select all elements with class2 having parent with class1
- selector="[input=text]" - will select all elements with input type text
Any valid CSS string can be used in this method.
If string matches then its return collection of HTML elements matching the string else return null.
6. querySelector() Method
querySelector() method is the same as
querySelectorAll(), the only difference is that it returns only the 1st element that matches the CSS string.