Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Add a Class to DOM Element in JavaScript?
Next article icon

JavaScript - How to Manipulate DOM Elements?

Last Updated : 02 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The DOM stands for the Document Object Model (DOM), which allows us to interact with the document and change its structure, style, and content. We can use the DOM to change the content and style of an HTML element by changing its properties.

In this article, we will discuss how to manipulate the DOM elements.

How to Manipulate DOM Elements?

We can manipulate or change the DOM elements by using the following methods:

1. Change the Content of an Element

You can change the content inside an HTML element using JavaScript. The two most common properties for this are innerHTML and textContent:

  • innerHTML: Allows you to get or set the HTML content inside an element.
  • textContent: Allows you to get or set the text content inside an element, ignoring any HTML tags.
HTML
<body>     <div id="example1">This is the original content using innerHTML.</div>     <div id="example2">This is the original text content using textContent.</div>      <button onclick="changeContent()">Change Content</button>      <script>         // Function to change content         function changeContent() {             document.getElementById("example1").innerHTML =              "<strong>This is changed using innerHTML!</strong>";              document.getElementById("example2").textContent =              "This is changed using textContent!";         }     </script> </body> 

Output

Animationkk
DOM Manipulation - Change the Content of an Element

In this example

  • innerHTML changes the entire content of an element, including HTML tags. In this case, we replace the content of the first div with bold text using <strong>.
  • textContent changes only the text inside the element, ignoring any HTML tags. The second div is updated with plain text, without any HTML formatting.
  • The first div shows "This is the original content using innerHTML."
  • The second div shows "This is the original text content using textContent."
  • After clicking the "Change Content" button.
  • The first div will display "This is changed using innerHTML!" with bold text.
  • The second div will display "This is changed using textContent!" with plain text.

2. Manipulate the Class Attribute

You can add, remove, or toggle classes on an element using JavaScript. This is helpful for styling or applying animations.

  • classList.add(): Adds a class to an element.
  • classList.remove(): Removes a class from an element.
  • classList.toggle(): Toggles a class (adds it if it's not present, removes it if it is).
HTML
<html> <head>     <style>         .highlight {             color: red;             font-weight: bold;         }         .bold {             font-weight: bold;         }     </style> </head> <body>     <div id="example" class="bold">This is a text element with the "bold" class.</div>      <button onclick="addClass()">Add 'highlight' Class</button>     <button onclick="removeClass()">Remove 'bold' Class</button>     <button onclick="toggleClass()">Toggle 'highlight' Class</button>     <script>         function addClass() {             document.getElementById("example").classList.add("highlight");         }         function removeClass() {             document.getElementById("example").classList.remove("bold");         }         function toggleClass() {             document.getElementById("example").classList.toggle("highlight");         }     </script> </body> </html> 

Output:

Animationkk
Dom Manipulation - Manipulate the Class Attribute

In this example

  • Adding a Class (addClass()): When you click the "Add 'highlight' Class" button, the highlight class is added to the div element with the id="example". This changes the text color to red and makes it bold (as defined in the CSS).
  • Removing a Class (removeClass()): When you click the "Remove 'bold' Class" button, the bold class is removed from the div, which removes the bold styling from the text.
  • Toggling a Class (toggleClass()): When you click the "Toggle 'highlight' Class" button, the highlight class is either added or removed, depending on whether it's already present. If the class is present, it will be removed; if not, it will be added.

3. Set CSS Styles Using JavaScript

You can directly manipulate the CSS styles of an element using the style property. This allows you to dynamically change how elements appear on the page.

JavaScript
// Changing multiple CSS properties document.getElementById("demo").style.color = "red"; document.getElementById("demo").style.fontSize = "20px"; // Adding more than one style document.getElementById("demo").style.cssText = "color: blue; font-size: 18px;"; 

4. Create, Add, and Remove Elements

Sometimes, you need to create new elements, add them to the DOM, or remove existing ones. You can do this easily with the following methods

  • document.createElement(): Creates a new element.
  • appendChild(): Adds a new element to a parent element.
  • removeChild(): Removes a child element from a parent.
JavaScript
// Create a new element let newDiv = document.createElement("div"); newDiv.textContent = "This is a new div"; // Add the new element to the DOM document.body.appendChild(newDiv); // Remove an element from the DOM document.body.removeChild(newDiv); 

5. Insert Elements at a Specific Position

You can insert new elements at specific positions relative to existing elements using methods like insertBefore().

JavaScript
// Create a new element let newDiv = document.createElement("div"); newDiv.textContent = "This is a new div";  // Find an existing element to insert before let referenceNode = document.getElementById("referenceElement");  // Insert the new element before the reference element document.body.insertBefore(newDiv, referenceNode); 

6. Manipulate Element Attributes

You can easily get, set, or remove the attributes of an HTML element using the following methods:

  • getAttribute(): Retrieves the value of an attribute.
  • setAttribute(): Sets a new value for an attribute.
  • removeAttribute(): Removes an attribute.
JavaScript
// Get the value of an attribute let src = document.getElementById("image").getAttribute("src");  // Set a new value for an attribute document.getElementById("image").setAttribute("src", "new-image.jpg");  // Remove an attribute document.getElementById("image").removeAttribute("src"); 

7. Manipulate Data Attributes

HTML5 introduced data attributes, which are custom attributes that you can use to store extra information about an element. These are particularly useful for adding data to an element without affecting its visual structure.

  • dataset: A special property in JavaScript that allows you to access data attributes.
JavaScript
// Setting a data attribute document.getElementById("demo").dataset.userId = "12345"; // Getting a data attribute let userId = document.getElementById("demo").dataset.userId; console.log(userId); // Outputs: 12345 

Conclusion

Manipulating the DOM with JavaScript is a core aspect of web development. Understanding how to select, modify, and manipulate DOM elements enables you to create dynamic, interactive web applications. With the power to change text, styles, attributes, and even structure in real-time, JavaScript empowers developers to build rich, user-responsive websites.


Next Article
How to Add a Class to DOM Element in JavaScript?

M

mohithsharmajf3o
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions
  • JavaScript-DOM

Similar Reads

  • How to select DOM Elements in JavaScript ?
    Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or mo
    3 min read
  • Manipulating HTML Elements with JavaScript
    JavaScript is a powerful language that can be used to manipulate the HTML elements on a web page. By using JavaScript, we can access the HTML elements and modify their attributes, styles, and content. This allows us to create dynamic and interactive web pages. Methods to Identify the elements to man
    5 min read
  • How to Add an ID to Element in JavaScript ?
    In JavaScript, the ID is the unique identifier through which the elements can be identified and manipulated if required. We can add an ID to an element in JavaScript using various approaches that are explored in this article with practical demonstration. Below are the possible approaches: Table of C
    2 min read
  • How to Add a Class to DOM Element in JavaScript?
    Adding a class to a DOM (Document Object Model) element in JavaScript is a fundamental task that enables developers to dynamically manipulate the appearance and behavior of web pages. Classes in HTML provide a powerful way to apply CSS styles or JavaScript functionality to multiple elements at once.
    2 min read
  • How to Select and Manipulate CSS pseudo-elements using JavaScript / jQuery ?
    In this article, we will learn how to select and manipulate CSS pseudo-elements using JavaScript (or jQuery). CSS pseudo-elements allow developers to style and enhance specific parts of an HTML document with the help of selectors like::before and::after, which provide the flexibility to add decorati
    2 min read
  • How to dynamically create new elements in JavaScript ?
    New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method. The examples given below would demonstrate this approach. Example 1: In this example, a newly created element is added as a
    3 min read
  • How To Get Element By Class Name In JavaScript ?
    When working with the DOM in JavaScript, selecting elements by their class names is a common task. JavaScript provides several methods to achieve this, whether we need to select one or multiple elements. In this article, we will cover different approaches to get elements by class name in JavaScript.
    3 min read
  • How to Select an Element by ID in JavaScript ?
    In JavaScript, we can use the "id" attribute to interact with HTML elements. The "id" attribute in HTML assigns a unique identifier to an element. This uniqueness makes it easy for JavaScript to precisely target and manipulate specific elements on a webpage. Selecting elements by ID helps in dynamic
    2 min read
  • How to remove an HTML element using JavaScript ?
    Removing an HTML element using JavaScript involves deleting it from the DOM, typically using methods like element.remove() or parentNode.removeChild(). This approach updates the webpage dynamically, allowing for responsive interactions by removing unwanted or outdated elements based on user actions
    3 min read
  • How to Toggle an Element Class in JavaScript ?
    In JavaScript, toggling an element class refers to the process of dynamically adding or removing a CSS class from an HTML element. This allows developers to easily change an element's appearance or behavior in response to user actions, such as clicks or events. These are the following methods for to
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences