LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

DOM Manipulation in JavaScript – Select and Modify HTML Elements

DOM stands for Document Object Model. It represents an HTML page as a structure of objects that JavaScript can access. DOM manipulation means selecting HTML elements and changing their content, styles, attributes or structure

DOM Manipulation in JavaScript – Select and Modify HTML Elements

Quick Answer: DOM manipulation lets JavaScript select HTML elements and change them while a page is open. You can update text, change styles, set attributes, create elements and remove elements. Methods like querySelector(), textContent and classList help you do this.

1. What Is DOM Manipulation in JavaScript?

Imagine a school website that displays student details and marks. The school wants to update a student's result without reloading the page.

HTML creates the page structure. CSS controls how that structure looks. JavaScript can change the structure and content while the page is running.

DOM = Document Object Model. It is the browser's object-based representation of an HTML page.

The browser reads HTML and builds a tree of elements. JavaScript can access those elements through the DOM.

How the Browser Connects HTML and JavaScript

HTML Page markup parse DOM Tree Browser objects access JavaScript Select and update The browser displays the updated page.

The browser builds a DOM tree from HTML, then JavaScript works with its elements.

2. Why Do We Need DOM Manipulation?

Imagine a school portal with 1,000 student records. Each student has a name, class and result.

How would the page show a changed result without refreshing the whole page? Think about how the browser could update only the required information.

The Problem Without DOM Manipulation

Consider this simple student result card. Its content is fixed in HTML.

Example 1: Static Student Result Card

Save this as an HTML file and open it in a browser.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Student Result</title>
</head>
<body>
  <h2>Priya's Result</h2>
  <p>Marks: 72</p>
  <p>Result: Pass</p>
</body>
</html>

Expected browser display

Priya's Result
Marks: 72
Result: Pass

This works, but the values are fixed in the HTML. A developer must change the markup to show another result.

What Goes Wrong as the Portal Grows?

  1. Every result change may need a page update.
  2. Repeated HTML becomes harder to maintain.
  3. Different screen sections can show outdated information.
  4. Adding new student records becomes more work.

Now think about 1,000 students. Updating every card manually is not practical.

The Solution With DOM Manipulation

JavaScript can select the result elements and update their content. The HTML structure can remain in place.

Example 2: Update a Student Result with JavaScript

Save this complete example as an HTML file and open it in a browser.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Student Result</title>
</head>
<body>
  <h2 id="studentName">Priya's Result</h2>
  <p>Marks: <span id="studentMarks">72</span></p>
  <p>Result: <span id="studentResult">Pending</span></p>

  <script>
    const marks = 72;

    document.getElementById("studentMarks").textContent = marks;

    const resultElement =
      document.getElementById("studentResult");

    resultElement.textContent =
      marks >= 40 ? "Pass" : "Fail";
  </script>
</body>
</html>

Expected browser display

Priya's Result
Marks: 72
Result: Pass
Static HTML compared with DOM manipulation
Without DOM manipulation With DOM manipulation
Values stay fixed in the markup. JavaScript updates values at runtime.
Changes need HTML edits. Selected elements can change directly.
Repeated updates become difficult. One reusable function can update many records.
Dynamic page updates need extra work. Updates can happen without a full page reload.

The Idea to Remember

  • DOM = the browser's object representation of a page.
  • Element = one HTML item, such as a heading or paragraph.
  • Selector = a way to find an element.
  • Property = information or content available on an element.
  • Method = an action an object can perform.
  • DOM manipulation = selecting and changing page elements with JavaScript.

3. How to Select HTML Elements

Before changing an element, JavaScript needs to find it. The DOM provides several selection methods.

3.1 getElementById()

This method selects one element by its unique ID. It returns the matching element or null when no match exists.

Example 3: Select a Student Name by ID

<h2 id="studentName">Priya</h2>

<script>
  const student =
    document.getElementById("studentName");

  console.log(student.textContent);
</script>

Expected console output

Priya

3.2 querySelector()

This method selects the first element that matches a CSS selector. You can use an ID, class or element name.

Example 4: Select Elements Using CSS Selectors

<h2 id="studentName">Priya</h2>
<p class="student-result">Pass</p>

<script>
  const name =
    document.querySelector("#studentName");

  const result =
    document.querySelector(".student-result");

  const heading =
    document.querySelector("h2");

  console.log(name.textContent);
  console.log(result.textContent);
  console.log(heading.textContent);
</script>

Expected console output

Priya
Pass
Priya

3.3 querySelectorAll()

This method selects every element matching a CSS selector. It returns a NodeList, which you can loop through.

Example 5: Select All Student Marks

<p class="student-mark">72</p>
<p class="student-mark">85</p>
<p class="student-mark">91</p>

<script>
  const marks =
    document.querySelectorAll(".student-mark");

  marks.forEach(function (mark) {
    console.log(mark.textContent);
  });
</script>

Expected console output

72
85
91

3.4 getElementsByClassName() and getElementsByTagName()

These methods select elements by class name or tag name. They return live HTMLCollections.

A live collection reflects matching changes in the document. A NodeList from querySelectorAll() is static.

Example 6: Select by Class and Tag

<p class="student-mark">72</p>
<p class="student-mark">85</p>

<script>
  const byClass =
    document.getElementsByClassName("student-mark");

  const byTag =
    document.getElementsByTagName("p");

  console.log(byClass.length);
  console.log(byTag.length);
</script>

Expected console output

2
2

Selector Methods at a Glance

Common JavaScript DOM selection methods
Method What it selects Return value
getElementById() One element by ID Element or null
querySelector() First CSS selector match Element or null
querySelectorAll() All CSS selector matches Static NodeList
getElementsByClassName() Elements with a class Live HTMLCollection
getElementsByTagName() Elements with a tag name Live HTMLCollection

4. How to Change HTML Content

After selecting an element, you can change its displayed content. Three common properties are textContent, innerText and innerHTML.

4.1 textContent

textContent reads or changes the text inside an element. It treats the assigned value as text, not HTML.

Example 7: Change the Result Message

<h2 id="resultMessage">Result Pending</h2>

<script>
  const message =
    document.getElementById("resultMessage");

  message.textContent = "Priya has passed!";
</script>

Expected browser display

Priya has passed!

4.2 innerText

innerText reads or changes rendered text. It considers the visible layout and CSS styling.

Example 8: Read Visible Text

<div id="studentDetails">
  <p>Name: Priya</p>
  <p style="display:none">Internal Note</p>
</div>

<script>
  const details =
    document.getElementById("studentDetails");

  console.log(details.innerText);
</script>

Expected console output

Name: Priya

4.3 innerHTML

innerHTML reads or changes the HTML markup inside an element. Use it only with trusted or safely created content.

Example 9: Add HTML Content

<div id="studentDetails"></div>

<script>
  const details =
    document.getElementById("studentDetails");

  details.innerHTML =
    "<strong>Priya</strong> - Pass";
</script>

Expected browser display

Priya - Pass
(Priya appears in bold.)

Security warning: Avoid putting untrusted user input into innerHTML. It can create cross-site scripting risks. Prefer textContent for plain text.

textContent vs innerText vs innerHTML

Differences between common content properties
Property Purpose Important detail
textContent Read or set text Does not parse HTML markup.
innerText Read or set rendered text Considers rendered visibility and layout.
innerHTML Read or set HTML markup Parses assigned markup as HTML.

5. How to Change CSS Styles and Classes

JavaScript can change how an element looks. You can update inline styles or add and remove CSS classes.

5.1 Change Styles Using style

The style property changes inline CSS declarations on an element.

Example 10: Highlight a Passing Result

<p id="studentResult">Pass</p>

<script>
  const result =
    document.getElementById("studentResult");

  result.style.color = "green";
  result.style.fontWeight = "bold";
  result.style.backgroundColor = "#dcfce7";
</script>

Expected browser appearance

Pass
Green, bold text on a light green background.

5.2 Change Classes Using classList

classList helps you add, remove, toggle or check CSS classes.

Example 11: Add a Result Class

<style>
  .passed {
    color: green;
    font-weight: bold;
  }
</style>

<p id="studentResult">Pass</p>

<script>
  const result =
    document.getElementById("studentResult");

  result.classList.add("passed");
  console.log(result.classList.contains("passed"));

  result.classList.remove("passed");
</script>

Expected console output

true

These are the most useful class methods:

  • add() adds a class.
  • remove() removes a class.
  • toggle() adds or removes a class.
  • contains() checks whether a class exists.
  • replace() replaces one class with another.

6. How to Change HTML Attributes

Attributes provide extra information about HTML elements. Examples include id, title, src and disabled.

You can read, add, change or remove attributes using DOM methods.

Example 12: Update an Image Attribute

<img
  id="studentPhoto"
  src="student-old.jpg"
  alt="Student photograph">

<script>
  const photo =
    document.getElementById("studentPhoto");

  photo.setAttribute("src", "student-new.jpg");
  photo.setAttribute("alt", "Priya's photograph");

  console.log(photo.getAttribute("src"));

  photo.removeAttribute("title");
</script>

Expected console output

student-new.jpg

Remember these attribute methods:

  • getAttribute() reads an attribute.
  • setAttribute() adds or changes an attribute.
  • removeAttribute() removes an attribute.
  • hasAttribute() checks whether an attribute exists.

7. How to Create and Remove HTML Elements

Sometimes the page needs new elements. JavaScript can create them and add them to the DOM.

7.1 createElement() and appendChild()

createElement() creates a new element. appendChild() adds it inside another element.

Example 13: Add a Student to a List

<ul id="studentList">
  <li>Priya</li>
</ul>

<script>
  const list =
    document.getElementById("studentList");

  const newStudent =
    document.createElement("li");

  newStudent.textContent = "Ravi";

  list.appendChild(newStudent);
</script>

Expected browser display

Priya
Ravi

7.2 append(), prepend() and before()

These methods place nodes or text at different positions. They are useful when building dynamic lists.

Example 14: Insert Students at Different Positions

<ul id="studentList">
  <li id="firstStudent">Priya</li>
</ul>

<script>
  const list =
    document.getElementById("studentList");

  const firstStudent =
    document.getElementById("firstStudent");

  const ravi = document.createElement("li");
  ravi.textContent = "Ravi";

  const lakshmi = document.createElement("li");
  lakshmi.textContent = "Lakshmi";

  list.append(ravi);
  list.prepend(lakshmi);

  const arjun = document.createElement("li");
  arjun.textContent = "Arjun";

  firstStudent.before(arjun);
</script>

Expected browser display

Lakshmi
Arjun
Priya
Ravi

7.3 remove() and removeChild()

You can remove an element when it is no longer needed. Use remove() or its parent's removeChild() method.

Example 15: Remove a Student

<ul id="studentList">
  <li id="studentPriya">Priya</li>
  <li id="studentRavi">Ravi</li>
</ul>

<script>
  const ravi =
    document.getElementById("studentRavi");

  ravi.remove();

  const priya =
    document.getElementById("studentPriya");

  priya.parentElement.removeChild(priya);
</script>

Expected browser display

The student list is now empty.

8. DOM Manipulation Workflow – Three Visual Animations

Let's connect the main ideas through a school result portal. These diagrams show three separate workflows.

Animation 1: Select an Element and Update Its Text

DOM Selection and Text Update

STAGE 01 Find the student result STAGE 02 getElementById("studentResult") STAGE 03 textContent = "Pass" Updated result appears on the page

The animation highlights selection, text assignment and the final browser update.

Animation 2: Change the Result's Appearance

Class and Style Update Pipeline

STAGE 01 Select the result element STAGE 02 classList.add("passed") STAGE 03 Browser applies the CSS class PASS · Green highlighted result

The selected element receives a CSS class, and the browser applies its styles.

Animation 3: Create and Insert a New Student

Dynamic Student List Construction

STAGE 01 createElement("li") STAGE 02 Set textContent to "Ravi" STAGE 03 appendChild(newStudent) Student list now contains Ravi

A new list item is created, filled with text and inserted into the existing list.

9. Complete Practical Example: Interactive Student Result Portal

Now let's combine selection, content updates, classes and element creation. This example uses one school result card.

When you click the buttons, the page updates without reloading. It also adds a new student to the list.

Example 16: Complete Interactive Student Portal

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Student Result Portal</title>
  <style>
    .passed {
      color: green;
      font-weight: bold;
    }

    .failed {
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h2 id="studentName">Priya</h2>
  <p>Marks: <span id="studentMarks">72</span></p>
  <p>Result: <span id="studentResult">Pending</span></p>

  <button id="passButton">Show Result</button>
  <button id="addButton">Add Student</button>

  <h3>Student List</h3>
  <ul id="studentList">
    <li>Priya</li>
  </ul>

  <script>
    const marks = 72;

    const resultElement =
      document.getElementById("studentResult");

    const marksElement =
      document.getElementById("studentMarks");

    const passButton =
      document.getElementById("passButton");

    const addButton =
      document.getElementById("addButton");

    const studentList =
      document.getElementById("studentList");

    marksElement.textContent = marks;

    passButton.addEventListener("click", function () {
      const passed = marks >= 40;

      resultElement.textContent =
        passed ? "Pass" : "Fail";

      resultElement.classList.remove("passed", "failed");

      resultElement.classList.add(
        passed ? "passed" : "failed"
      );
    });

    addButton.addEventListener("click", function () {
      const newStudent =
        document.createElement("li");

      newStudent.textContent = "Ravi";

      studentList.appendChild(newStudent);

      addButton.disabled = true;
    });
  </script>
</body>
</html>

How to run it: Save the code as student-result.html. Open the file in a browser. Select Show Result, then Add Student.

Expected browser behavior

Priya
Marks: 72
Result: Pass

Student List
Priya
Ravi

Try the Interactive Result Card

Priya's Result

Marks: 72

Result: Pending

Select an action to update the result.

  • Priya

Step-by-Step Code Breakdown

  1. Select the elements: The code uses getElementById() to find page elements.
  2. Read the marks: The marks variable stores Priya's result.
  3. Listen for a click: addEventListener() runs a function when a button is clicked.
  4. Check the result: The condition checks whether marks are at least 40.
  5. Update the text: The textContent property changes the displayed result.
  6. Update the class: The classList methods apply the correct result style.
  7. Create a new item: The code creates an li element and appends it.
  8. Prevent duplicate clicks: The Add Student button becomes disabled after insertion.

10. Common DOM Manipulation Mistakes

Mistake 1: Selecting an Element That Does Not Exist

A selector can return null. Accessing its properties then causes an error.

Incorrect approach

const result =
  document.getElementById("missingResult");

result.textContent = "Pass";

Correct approach

const result =
  document.getElementById("studentResult");

if (result) {
  result.textContent = "Pass";
}

Always check that an element exists before using it.

Mistake 2: Running JavaScript Before HTML Loads

If the script runs before the browser creates an element, the selector may return null.

Correct approach using defer

<script src="student.js" defer></script>

The defer attribute runs the external script after HTML parsing finishes.

Mistake 3: Using innerHTML for Plain Text

Do not use HTML parsing when you only need to show text.

Prefer textContent for plain text

const message =
  document.getElementById("studentMessage");

message.textContent = userEnteredName;

This avoids treating the supplied value as HTML markup.

Mistake 4: Using the Wrong Selector

An ID selector starts with #. A class selector starts with ..

Correct selector examples

document.querySelector("#studentName");
document.querySelector(".student-result");
document.querySelectorAll("li");

Mistake 5: Adding Duplicate Elements

A button can create repeated items if users click it many times. Disable the button or check whether the item already exists.

Avoid duplicate student entries

const list =
  document.getElementById("studentList");

const existing =
  list.querySelector('[data-student="Ravi"]');

if (!existing) {
  const item = document.createElement("li");

  item.textContent = "Ravi";
  item.dataset.student = "Ravi";

  list.appendChild(item);
}

11. DOM Manipulation Best Practices

  • Use getElementById() when selecting by a unique ID.
  • Use querySelector() for flexible CSS selectors.
  • Use querySelectorAll() when selecting multiple matching elements.
  • Prefer textContent when displaying plain text.
  • Avoid inserting untrusted input through innerHTML.
  • Use CSS classes for reusable visual changes.
  • Use event listeners instead of inline HTML event attributes.
  • Check for missing elements before changing them.
  • Keep JavaScript in separate files for larger applications.
  • Use event delegation when many similar child elements need event handling.

12. Performance and Real-World Considerations

DOM operations are useful, but large numbers of updates can affect page performance.

Reduce Repeated DOM Selection

If you use the same element many times, store its reference. This keeps the code easier to read.

Example 17: Store an Element Reference

const result =
  document.getElementById("studentResult");

result.textContent = "Pass";
result.classList.add("passed");

Build Multiple Elements Before Inserting

For a large list, a DocumentFragment can help group new nodes before insertion. It is a lightweight container that is not part of the visible document tree.

Example 18: Insert Multiple Students

const list =
  document.getElementById("studentList");

const fragment =
  document.createDocumentFragment();

const students = ["Priya", "Ravi", "Lakshmi"];

students.forEach(function (name) {
  const item = document.createElement("li");

  item.textContent = name;

  fragment.appendChild(item);
});

list.appendChild(fragment);

This groups the new nodes before adding them to the page. Measure performance before assuming it will improve every case.

Use Event Delegation for Repeated Items

Event delegation places one event listener on a parent. The parent handles events from matching child elements.

Example 19: Handle Student List Clicks

const list =
  document.getElementById("studentList");

list.addEventListener("click", function (event) {
  if (event.target.matches("li")) {
    console.log(event.target.textContent);
  }
});

This can reduce the number of event listeners in a large list.

13. DOM Manipulation Interview Questions

1. What Is the DOM?

What the interviewer wants: They want to know how JavaScript accesses HTML.

Strong answer: "DOM means Document Object Model. The browser creates a tree of objects from HTML. JavaScript uses this tree to read and update page elements. For example, I can update Priya's result without reloading the school portal."

2. What Is the Difference Between querySelector() and querySelectorAll()?

Strong answer: "querySelector returns the first matching element. querySelectorAll returns all matching elements in a static NodeList. I use querySelector for one result card and querySelectorAll for many student marks."

3. What Is the Difference Between innerHTML and textContent?

Strong answer: "textContent reads or sets text. It does not parse the value as HTML. innerHTML reads or sets markup. I prefer textContent for user input because it avoids HTML parsing."

4. What Is the Difference Between NodeList and HTMLCollection?

Strong answer: "A NodeList from querySelectorAll is static. An HTMLCollection from methods like getElementsByClassName is live. A live collection reflects matching DOM changes."

5. What Is Event Delegation?

Strong answer: "Event delegation uses one listener on a parent element. The parent handles events from matching child elements. For a student list, one listener can handle clicks on many student rows."

6. How Can You Prevent Cross-Site Scripting Through DOM Updates?

Strong answer: "I avoid placing untrusted values into innerHTML. For plain text, I use textContent. If HTML is genuinely needed, I use a trusted sanitization approach and follow the application's security rules."

14. Hands-On Practice

Beginner Exercises

  1. Select a heading using getElementById() and change its text.
  2. Select all student marks using querySelectorAll().
  3. Change a result message using textContent.

Intermediate Exercises

  1. Add a CSS class when a student passes.
  2. Change an image's alt attribute.
  3. Create a new student list item using createElement().
  4. Add a button that removes a selected student.

Advanced Exercises

  1. Build a student result table with dynamic rows.
  2. Add event delegation to handle row selection.
  3. Use a DocumentFragment to add several students.
  4. Build a search box that filters student records as the user types.

Challenge: Build a Student Result Manager

Create a small page that manages student records. Each record should show a name, marks and result.

  • Add a new student through an input field.
  • Calculate Pass or Fail using a 40-mark threshold.
  • Highlight passing and failing results with CSS classes.
  • Remove a student when the user selects a delete button.
  • Prevent empty student names from being added.

Hint: Use createElement(), textContent, appendChild() and addEventListener().

15. Frequently Asked Questions

Can JavaScript change HTML without reloading the page?

Yes. JavaScript can update the DOM while the page is open. The browser displays the changed content without a full page reload.

Which DOM selector should beginners learn first?

Start with getElementById() and querySelector(). Then learn querySelectorAll() for multiple elements.

Is innerHTML safe?

It depends on the content. Avoid assigning untrusted input directly to innerHTML. Use textContent for plain text.

What is the difference between DOM and HTML?

HTML is the markup used to describe a page. The DOM is the browser's object representation of that page. JavaScript works with the DOM.

Can JavaScript create new HTML elements?

Yes. Use document.createElement() to create an element. Then insert it using methods such as appendChild() or append().

16. Next Steps and Community

You now know how JavaScript selects and changes HTML elements. You have also learned how to update text, styles, attributes and page structure.

Try It Yourself

Build the Student Result Manager challenge. Test each operation in your browser's developer tools.

Explore Further

Share Your Knowledge

Share your DOM examples and improvements with the Upgradix learning community. Discuss different ways to build clean and accessible interfaces. Help other learners understand JavaScript through practical examples.

Keep practising DOM manipulation. Small updates are the foundation of interactive web applications.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.