DOM Methods in JavaScript

DOM (Document Object Model) methods in JavaScript are essential tools for interacting with web page elements dynamically. These methods enable developers to access, manipulate, and modify HTML elements, attributes, and content on a web page. Understanding DOM methods is crucial for creating dynamic and responsive web applications.

Basic DOM Manipulation Methods

JavaScript provides several basic DOM manipulation methods for accessing and modifying elements on a web page.

  • getElementById: This method retrieves an element from the document by its unique ID.
  • getElementsByClassName: It returns a collection of elements with the specified class name.
  • getElementsByTagName: This method retrieves elements by their tag name.
  • querySelector and querySelectorAll: These methods allow developers to select elements using CSS selectors.
				
					// Example of basic DOM manipulation methods
var elementById = document.getElementById('myElementId');
console.log(elementById);

var elementsByClass = document.getElementsByClassName('myClassName');
console.log(elementsByClass);

var elementsByTag = document.getElementsByTagName('div');
console.log(elementsByTag);

var elementByQuery = document.querySelector('.myClass');
console.log(elementByQuery);

var elementsByQueryAll = document.querySelectorAll('.myClass');
console.log(elementsByQueryAll);

				
			

Explanation

  1. var elementById = document.getElementById('myElementId');

    • This line selects an element from the document with the ID ‘myElementId’ using the getElementById method. It then assigns this element to the variable elementById.
  2. console.log(elementById);

    • This line logs the element selected by ID to the console. It helps you verify that the correct element has been selected.
  3. var elementsByClass = document.getElementsByClassName('myClassName');

    • This line selects all elements in the document that have the class name ‘myClassName’ using the getElementsByClassName method. It stores these elements in the variable elementsByClass, which is a collection of elements.
  4. console.log(elementsByClass);

    • This line logs the collection of elements with the class name ‘myClassName’ to the console. It allows you to see all the elements that were selected by class name.
  5. var elementsByTag = document.getElementsByTagName('div');

    • This line selects all <div> elements in the document using the getElementsByTagName method. It stores these elements in the variable elementsByTag, which is a collection of <div> elements.
  6. console.log(elementsByTag);

    • This line logs the collection of <div> elements to the console. It helps you verify that the correct elements have been selected by tag name.
  7. var elementByQuery = document.querySelector('.myClass');

    • This line selects the first element in the document that matches the CSS selector ‘.myClass’ using the querySelector method. It assigns this element to the variable elementByQuery.
  8. console.log(elementByQuery);

    • This line logs the element selected by the CSS selector ‘.myClass’ to the console. It helps you verify that the correct element has been selected using the CSS selector.
  9. var elementsByQueryAll = document.querySelectorAll('.myClass');

    • This line selects all elements in the document that match the CSS selector ‘.myClass’ using the querySelectorAll method. It stores these elements in the variable elementsByQueryAll, which is a collection of elements.
  10. console.log(elementsByQueryAll);

    • This line logs the collection of elements selected by the CSS selector ‘.myClass’ to the console. It allows you to see all the elements that were selected by the CSS selector.

Manipulating Element Content and Attributes

DOM methods also enable developers to manipulate the content and attributes of HTML elements dynamically.

  • textContent: It sets or returns the text content of an element and its descendants.
  • innerHTML: This property sets or returns the HTML content of an element.
  • setAttribute: It sets the value of an attribute on the specified element.
				
					// Example of manipulating element content and attributes
var element = document.getElementById('myElement');
element.textContent = 'New content';
element.innerHTML = '<strong>New content</strong>';
element.setAttribute('class', 'newClass');

				
			

Explanation

 This code retrieves an element with the ID ‘myElement’ from the document and stores it in the variable element. It then sets the text content of the element to ‘New content’, changes its inner HTML to ‘<strong>New content</strong>’, and adds a ‘newClass’ attribute to the element.

Creating and Removing Elements

JavaScript provides methods for creating and removing elements dynamically, allowing developers to add or remove content from the DOM as needed.

  • createElement: This method creates a new element with the specified tag name.
  • appendChild: It adds a new child node to the end of the list of children of a specified parent node.
  • removeChild: This method removes a child node from the DOM.
				
					// Example of creating and removing elements
var newElement = document.createElement('div');
newElement.textContent = 'New element';
document.body.appendChild(newElement);

var elementToRemove = document.getElementById('elementToRemove');
elementToRemove.parentNode.removeChild(elementToRemove);

				
			

Certainly! Here’s the explanation with proper formatting:

1. `var newElement = document.createElement(‘div’);`: This line creates a new `<div>` element and assigns it to the variable `newElement`.

2. `newElement.textContent = ‘New element’;`: Here, the text content of the newly created `<div>` is set to “New element”.

3. `document.body.appendChild(newElement);`: This appends the newly created `<div>` element to the end of the document’s body, making it visible on the webpage.

4. `var elementToRemove = document.getElementById(‘elementToRemove’);`: It selects an element with the ID ‘elementToRemove’ and stores it in the variable `elementToRemove`.

5. `elementToRemove.parentNode.removeChild(elementToRemove);`: This line removes the selected element (‘elementToRemove’) from the document by accessing its parent node and then using `removeChild` method.

Advanced DOM Manipulation Methods

Advanced DOM manipulation methods allow developers to perform complex operations on DOM elements, providing greater flexibility and control over the structure and behavior of web pages.

Traversing the DOM Tree

Traversing the DOM tree involves navigating through parent, child, and sibling nodes to locate specific elements or perform operations on them.

				
					// Example of traversing the DOM tree
var parentElement = document.getElementById('parentElement');
var firstChild = parentElement.firstChild;
var nextSibling = firstChild.nextSibling;
console.log(nextSibling);

				
			

Explanation: In this example, we start with a parent element and access its first child node. Then, we navigate to the next sibling node of the first child. This allows us to traverse the DOM tree and access adjacent elements.

Handling Events

Event handling is a crucial aspect of web development, allowing developers to respond to user interactions such as clicks, mouse movements, and keyboard inputs.

				
					// Example of event handling
var button = document.getElementById('myButton');
button.addEventListener('click', function(event) {
    console.log('Button clicked!');
});

				
			

Explanation: Here, we add an event listener to a button element. When the button is clicked, the associated callback function is executed, logging a message to the console. Event handling enables developers to create interactive and responsive web applications.

Manipulating Element Styles and Classes

JavaScript allows developers to modify the visual appearance of elements by manipulating their CSS styles and classes dynamically.

				
					// Example of manipulating element styles and classes
var element = document.getElementById('myElement');
element.style.backgroundColor = 'blue';
element.classList.add('highlight');

				
			

Explanation: In this example, we change the background color of an element to blue and add a CSS class named ‘highlight’ to it. Manipulating element styles and classes dynamically allows developers to create visually appealing and interactive user interfaces.

Working with Forms

JavaScript enables developers to interact with HTML forms, retrieve user input, and validate form data using various DOM methods and properties.

				
					// Example of working with forms
var form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
    event.preventDefault();
    var input = document.getElementById('textInput');
    console.log('User entered: ' + input.value);
});

				
			

Explanation: Here, we add an event listener to a form element to handle form submission. We prevent the default form submission behavior using event.preventDefault(), then retrieve the value entered by the user in a text input field and log it to the console. Working with forms using DOM manipulation methods allows developers to create interactive and user-friendly web forms.

DOM methods in JavaScript are powerful tools for creating dynamic and interactive web applications. By mastering these methods, developers can efficiently manipulate the content, structure, and style of HTML elements, enabling the creation of engaging user experiences on the web. Understanding basic and advanced DOM manipulation techniques is essential for any JavaScript developer looking to build modern web applications. Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India