Modifying DOM | Dataplexa

Modifying the DOM

Selecting elements is only the first step. The real power of JavaScript comes from changing what users see and how the page behaves.

Modifying the DOM allows JavaScript to update text, styles, and structure of a web page dynamically.


Why Modify the DOM?

Modern websites are interactive. Content changes without page reloads, buttons respond instantly, and messages update in real time.

All of this happens by modifying the DOM.


Changing Text Content

You can change the text inside an element using innerText or textContent.


let title = document.getElementById("pageTitle");
title.innerText = "Welcome to Dataplexa";
  

This updates the visible text on the page.


Changing HTML Content

Sometimes you may want to insert HTML inside an element. For this, JavaScript provides innerHTML.


let container = document.getElementById("contentBox");
container.innerHTML = "Content updated!";
  

Use innerHTML carefully to avoid security issues.


Changing Styles

JavaScript can change CSS styles directly.


let box = document.getElementById("infoBox");
box.style.backgroundColor = "#e0f2fe";
box.style.padding = "20px";
  

This is useful for highlighting elements or showing states.


Adding and Removing Classes

A cleaner way to modify styles is by using CSS classes.


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

message.classList.add("active");
message.classList.remove("hidden");
  

This keeps styling logic in CSS and behavior in JavaScript.


Real-World Example

Imagine showing a success message after a form submission:


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

status.innerText = "Form submitted successfully";
status.classList.add("success");
  

Users immediately see feedback without reloading the page.


Common Beginner Mistakes

  • Overusing innerHTML
  • Mixing too much styling inside JavaScript
  • Trying to modify elements that don’t exist

Always keep structure, style, and behavior separate.


Thumb Rules

  • Use innerText for simple text updates
  • Prefer class changes over inline styles
  • Modify the DOM only when needed
  • Keep DOM operations readable and minimal

What Comes Next?

Now that you can change page content, the next step is responding to user actions.

In the next lesson, we will learn about events.