JavaScript DOM Methods

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 DOM Methods

Javascript provides us with different method that is very useful for finding an element within the document. Followings are the methods of DOM:

  • document.getElementById()
  • document.getElementsByClassName()
  • document.getElementsByTagName()
  • document.querySelector()
  • document.querySelectorALL()

HTML Element Selection Using ID

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.

General Syntax
      document.getElementById("elementId") ;
    
Try it now

Source Code

          
            var username=document.getElementById("username").value;  
document.write("Username name is :"+username);          
        
Try it now

Selection Of HTML Elements by Class Name

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.

General Syntax
      document.getELementsByClassName('elementClassName');
    
Try it now

Source Code

          
            var totalElement=document.getElementsByClassName('test');  
document.write("Total number of elements: <br>"+totalElement.length);          
        
Try it now

HTML Element Selection By Tag Name

HTML element can also be selected by their tag name using getElementsByTagName() method. It also returns array-like object with the given tag name.

General Syntax
      document.getElementsByTagName("elementTagName");
    
Try it now

Source Code

          
            var elem = document.getElementsByTagName("p");          
        
Try it now

Selecting HTML Elements With CSS Selectors

Javascript querySelectorAll() method is used to select HTML elements that matches the specified CSS selector(id, class names, types, attributes, values of attributes, etc).

General Syntax
      document.querySelectorAll(selector);
    
Try it now

Source Code

          
            var elem = document.querySelectorAll("p.test");          
        
Try it now

HTML Element Selection Using Element Name

Javascript getElementsByName() method is mainly used to select HTML element through their name property. It returns all the elements of the specified name.

General Syntax
      document.getElementsByName("ElementName");
    
Try it now

Source Code

          
            var users=document.getElementsByName("user");          
        
Try it now

Web Tutorials

JavaScript DOM Methods
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4