Javascript DOM Methods are used to select HTML elements and performs actions such as selecting an HTML element, creating a new element, changing the content of the element, changing CSS, removing elements, etc.
Javascript provides us with different method that is very useful for finding an element within the document. Followings are the methods of DOM:
The getElementById()
method is used to select element based on element unique Id.
Please keep in mind that the Id of every HTML element should be unique inside the web page. Two elements should not have the same Id on the same page.
Source Code
var username=document.getElementById("username").value;
document.write("Username name is :"+username);
The getElementsByClassName()
method is used to select the HTML elements through their class name and it returns the array-like objects that consist of all the elements having the specific class name.
Source Code
var totalElement=document.getElementsByClassName('test');
document.write("Total number of elements: <br>"+totalElement.length);
HTML element can also be selected by their tag name using getElementsByTagName()
method. It also returns array-like object with the given tag name.
Source Code
var elem = document.getElementsByTagName("p");
Javascript querySelectorAll() method is used to select HTML elements that matches the specified CSS selector(id, class names, types, attributes, values of attributes, etc).
Source Code
var elem = document.querySelectorAll("p.test");
Javascript getElementsByName()
method is mainly used to select HTML element through their name property. It returns all the elements of the specified name.
Source Code
var users=document.getElementsByName("user");