CS Engineering Gyan

JavaScript DOM Manipulation

DOM Manipulation is one of the most important concepts in JavaScript. It allows developers to access, modify, add, and remove HTML elements dynamically after a webpage has loaded.

The Document Object Model (DOM) creates a connection between JavaScript and HTML documents. Using DOM methods, JavaScript can change webpage content, styles, attributes, and structure according to user actions.

Interactive websites, dashboards, forms, animations, and modern web applications heavily depend on DOM manipulation.


What is DOM in JavaScript?

DOM stands for Document Object Model. It is a programming interface that represents an HTML document as a collection of objects.

When a browser loads an HTML page, it converts the complete document into a tree-like structure called the DOM Tree.

JavaScript uses this tree structure to access and control webpage elements.


Why is DOM Important?

HTML creates the structure of a webpage, CSS controls the design, and JavaScript adds behavior. DOM acts as a bridge between JavaScript and HTML.

Advantages of DOM Manipulation


Understanding DOM Tree

The browser represents HTML elements in the form of a tree structure.

Example HTML


<html>

    <body>

        <h1>

        Heading

        </h1>


        <p>

        Paragraph

        </p>


    </body>

</html>

The DOM structure looks like:


Document

 └── html

      └── body

           ├── h1

           └── p


DOM Document Object

The document object represents the entire HTML page loaded in the browser.

JavaScript uses this object to access HTML elements.

Example


document.write("Hello JavaScript");

Output


Hello JavaScript


Selecting HTML Elements in DOM

Before modifying any HTML element, JavaScript needs to select that element.

JavaScript provides several methods for selecting elements.


1. getElementById()

The getElementById() method selects an element using its unique id attribute.

Syntax


document.getElementById("id-name");

Example


<p id="message">

Hello

</p>


<script>


let text =
document.getElementById("message");


console.log(text);


</script>


2. getElementsByClassName()

This method selects multiple elements having the same class name.

Syntax


document.getElementsByClassName("class-name");

Example


let items =
document.getElementsByClassName("box");



3. getElementsByTagName()

This method selects elements using HTML tag names.

Example


let paragraphs =
document.getElementsByTagName("p");



4. querySelector()

The querySelector() method selects the first matching element using CSS selectors.

Example


let heading =
document.querySelector("h1");



5. querySelectorAll()

The querySelectorAll() method selects all matching elements.

Example


let buttons =
document.querySelectorAll("button");



Difference Between DOM Selection Methods

Method Purpose
getElementById() Select single element by id.
getElementsByClassName() Select elements by class.
getElementsByTagName() Select elements by tag.
querySelector() Select first matching CSS selector.
querySelectorAll() Select all matching CSS selectors.

Changing HTML Content

JavaScript can modify webpage text and HTML content using DOM properties.

innerHTML Property

The innerHTML property is used to change the HTML content inside an element.

Example


<p id="demo">

Old Text

</p>


<script>


document.getElementById("demo")
.innerHTML="New Text";


</script>

Output


New Text


Changing Text Using innerText

The innerText property changes only visible text content.

Example


document.getElementById("demo")
.innerText="Welcome JavaScript";



Changing CSS Styles Using DOM

JavaScript DOM allows developers to change the style of HTML elements dynamically. Using the DOM style property, we can modify colors, sizes, backgrounds, fonts, and many other CSS properties while the webpage is running.

Dynamic styling is commonly used for animations, themes, interactive buttons, and user interface improvements.


Changing Inline CSS Using style Property

The style property is used to access and modify CSS styles of selected elements.

Syntax


element.style.property = "value";

Example: Change Text Color


<p id="text">

JavaScript DOM

</p>


<script>


let paragraph =
document.getElementById("text");


paragraph.style.color = "blue";


</script>

Output


JavaScript DOM

(Text color changes to blue)


Changing Background Color

Example


let box =
document.getElementById("box");


box.style.backgroundColor = "yellow";

The background color of the selected element changes dynamically.


Changing Font Size Using DOM

Example


let heading =
document.querySelector("h1");


heading.style.fontSize = "40px";


Changing Multiple CSS Properties

Multiple styles can be modified using DOM.

Example


let element =
document.getElementById("demo");


element.style.color="green";

element.style.backgroundColor="black";

element.style.padding="20px";



Working with CSS Classes

Instead of changing every style property individually, JavaScript can add, remove, or toggle CSS classes using the classList property.


add() Method

The add() method adds a new CSS class to an element.

Example


let box =
document.getElementById("box");


box.classList.add("active");



remove() Method

The remove() method removes an existing CSS class.

Example


box.classList.remove("active");



toggle() Method

The toggle() method adds a class if it does not exist and removes it if it already exists.

Example


box.classList.toggle("dark");



contains() Method

The contains() method checks whether an element contains a specific class.

Example


let result =
box.classList.contains("active");


console.log(result);



Changing HTML Attributes Using DOM

HTML elements contain attributes such as id, class, src, href, and title. JavaScript can modify these attributes dynamically.


getAttribute() Method

The getAttribute() method is used to read the value of an attribute.

Example


let image =
document.getElementById("photo");


let source =
image.getAttribute("src");


console.log(source);



setAttribute() Method

The setAttribute() method is used to add or update an attribute value.

Example


let image =
document.getElementById("photo");


image.setAttribute(
"src",
"newimage.jpg"
);



removeAttribute() Method

The removeAttribute() method removes an attribute from an HTML element.

Example


button.removeAttribute("disabled");



Creating New HTML Elements

JavaScript can create new HTML elements dynamically using DOM methods.

This feature is useful for adding new content without refreshing the webpage.


createElement() Method

The createElement() method creates a new HTML element.

Syntax


document.createElement("tag-name");

Example


let heading =
document.createElement("h2");


heading.innerHTML =
"Welcome to CSE Gyan";



Adding Elements Using appendChild()

The appendChild() method adds a new element as the last child of another element.

Example


let paragraph =
document.createElement("p");


paragraph.innerHTML =
"New Paragraph";


document.body.appendChild(paragraph);


Output


New Paragraph


insertBefore() Method

The insertBefore() method inserts a new element before an existing element.

Example


parent.insertBefore(
newElement,
existingElement
);



Removing HTML Elements

JavaScript allows removing unwanted elements from the webpage dynamically.


removeChild() Method

The removeChild() method removes a child element from its parent.

Example


let item =
document.getElementById("item");


item.parentNode.removeChild(item);



remove() Method

Modern JavaScript provides the remove() method to directly delete an element.

Example


let element =
document.getElementById("box");


element.remove();



Replacing HTML Elements

The replaceChild() method replaces an existing element with a new element.

Example


parent.replaceChild(
newElement,
oldElement
);



DOM Navigation

DOM navigation allows accessing related elements such as parents, children, and siblings.

Important DOM Navigation Properties

Property Description
parentNode Returns parent element.
childNodes Returns child elements.
firstChild Returns first child.
lastChild Returns last child.
nextSibling Returns next element.
previousSibling Returns previous element.

Example: Accessing Parent Element


let child =
document.getElementById("child");


console.log(
child.parentNode
);



DOM Manipulation with Events

DOM manipulation becomes more powerful when combined with JavaScript events.

Users can interact with webpage elements, and JavaScript can modify the DOM according to those actions.

Example: Change Text on Button Click





Hello User



Working with Forms Using DOM

Forms are an important part of modern websites. JavaScript DOM allows developers to access form elements, read user input, validate information, and update form values dynamically.

Login pages, registration forms, search boxes, feedback forms, and payment systems commonly use DOM form manipulation.


Accessing Form Elements

JavaScript can access form elements using DOM selection methods like getElementById(), querySelector(), and form collections.

Example


<input type="text" id="username">


<script>


let user =
document.getElementById("username");


console.log(user);


</script>


Getting Input Value

The value property is used to read data entered by the user.

Example


<input type="text" id="name">


<script>


let username =
document.getElementById("name").value;


console.log(username);


</script>


Changing Input Value

JavaScript can also update input values dynamically.

Example


document.getElementById("name")
.value = "CSE Gyan";



Form Validation Using DOM

Form validation ensures that users enter correct and complete information before submitting data.

Example: Empty Field Validation


function checkForm()
{


let name =
document.getElementById("name").value;


if(name=="")
{

alert("Please Enter Name");

}

else
{

alert("Form Submitted");

}


}


Creating Dynamic Lists Using DOM

JavaScript can create and update lists dynamically without modifying HTML manually.

Dynamic lists are used in shopping carts, task managers, search suggestions, and notification systems.

Example: Add New List Item


let list =
document.createElement("li");


list.innerHTML="JavaScript";


document
.getElementById("subjects")
.appendChild(list);


Output


JavaScript


Creating Dynamic Tables

DOM allows developers to create table rows and cells dynamically based on data.

Example


let row =
document.createElement("tr");


let cell =
document.createElement("td");


cell.innerHTML="HTML";


row.appendChild(cell);


This technique is commonly used for displaying database records and API data.


Working with Images Using DOM

JavaScript can change images dynamically by modifying image attributes.

Example: Change Image Source


let image =
document.getElementById("photo");


image.src="new-image.jpg";



Creating Image Elements Dynamically


let img =
document.createElement("img");


img.src="picture.jpg";


document.body.appendChild(img);



DOM Animations

JavaScript DOM can be used to create simple animations by changing element styles repeatedly.

Animations are used for sliders, moving objects, effects, and interactive components.


Example: Moving Element


let box =
document.getElementById("box");


let position = 0;


function move()
{

position++;

box.style.left =
position+"px";

}


setInterval(move,10);



Changing Class Dynamically

Adding and removing classes allows developers to create animations and interactive designs easily.

Example


button.onclick=function()
{

box.classList.add("active");

}



Creating Popup Messages Using DOM

JavaScript can create dynamic messages and notifications using DOM elements.

Example


let message =
document.createElement("div");


message.innerHTML =
"Welcome User";


document.body.appendChild(message);



Practical DOM Manipulation Projects

DOM concepts are used to create many real-world applications.

1. To-Do List Application


2. Digital Clock


3. Image Gallery


4. Shopping Cart System


Difference Between HTML and DOM

HTML DOM
Creates webpage structure. Represents webpage as objects.
Static document. Dynamic programming model.
Cannot change automatically. Can modify content using JavaScript.
Written by developers. Created by browser automatically.

Common Mistakes While Using DOM


Best Practices for DOM Manipulation


JavaScript DOM Interview Questions

  1. What is DOM in JavaScript?
  2. Why is DOM used?
  3. What is the difference between HTML and DOM?
  4. Explain DOM tree structure.
  5. How can we select HTML elements using JavaScript?
  6. Difference between getElementById() and querySelector().
  7. What is innerHTML?
  8. Difference between innerHTML and innerText.
  9. How can we change CSS using DOM?
  10. How do you create a new HTML element?
  11. Explain appendChild() method.
  12. How can we remove an element from DOM?
  13. What is classList in JavaScript?
  14. How does JavaScript validate forms using DOM?
  15. What is the difference between DOM and BOM?

Summary

DOM Manipulation is a powerful JavaScript feature that allows developers to control and update webpage elements dynamically. Through the Document Object Model, JavaScript can access HTML elements, modify content, change styles, create new elements, remove elements, and handle user interactions.

Important DOM concepts include selecting elements, changing HTML content, modifying attributes, working with CSS classes, creating dynamic elements, form handling, and event-based updates.

A strong understanding of DOM manipulation is essential for developing interactive websites, modern web applications, dashboards, and user-friendly interfaces.


← Previous: JavaScript Events Next: JavaScript Form Validation →
Home Visit Our YouTube Channel