Getting Started with DOM Manipulation

Learn what the DOM is and how to use JavaScript to change a page’s content and structure dynamically.

🎯 Introduction

DOM manipulation lets you change a page’s content, styles, and structure with JavaScript, turning static text and images into an interactive experience. You can show or hide content on a button click, add elements dynamically, or update text. This is an essential skill for front-end development.


🌐 What Is the DOM, and Why Manipulate It?

DOM stands for Document Object Model. If a web page were a book, the DOM would be its electronic outline. The browser represents the page’s elements, text, images, and other content as nodes arranged in a tree called the DOM tree.

Think of the DOM as the page’s structure and content. Manipulating the DOM with JavaScript means changing this tree to update the page.

It is like using a television remote: pressing a button (JavaScript) changes what appears on the screen (the page content).

🛠️ Common Ways to Select DOM Nodes

Before manipulating the DOM, find the node (element) you want to work with, much like locating a page or paragraph in a book.

1. Find an Element by ID

An id uniquely identifies an element on a page. Use document.getElementById('elementId') to find it.

Example:

<div id="greeting">Hello, world!</div>

JavaScript:

var greet = document.getElementById('greeting');

2. Find Elements by Tag Name

This selects all elements with the given tag name, such as every <p> element.

var paragraphs = document.getElementsByTagName('p');

The result is a collection. Use an index to access a specific element.

3. Find Elements by Class Name

Elements with the same purpose or styling often share a class name.

var items = document.getElementsByClassName('item');

4. Use CSS Selectors

CSS selectors offer a flexible way to select elements by tag, class, ID, or position in the hierarchy.

var firstItem = document.querySelector('.item');
var allItems = document.querySelectorAll('.item');
querySelector returns the first matching element; querySelectorAll returns a list of all matching elements.

✏️ Updating DOM Node Content

Once you have an element, a common task is to change its text or HTML content.

Updating Text Content

Use the innerText or textContent property to update an element’s text.

var greet = document.getElementById('greeting');
greet.innerText = 'Hello, front-end beginner!';

Updating HTML Content

Use innerHTML when the replacement content includes HTML tags.

greet.innerHTML = '<strong>Hello, front-end beginner!</strong>';
Replacing content with innerHTML reparses the HTML and can remove event listeners attached to the replaced descendants.

➕ Adding and Removing Elements Dynamically

Besides updating content, you may need to add or remove parts of a page by manipulating element nodes.

1. Create an Element

Use document.createElement('tagName') to create an element.

var newDiv = document.createElement('div');
newDiv.innerText = 'This is newly added content';

2. Add an Element to the Page

Call appendChild on the parent element.

var container = document.getElementById('container');
container.appendChild(newDiv);

This adds the new element to the end of the container.

3. Remove an Element

Call removeChild on the parent element.

container.removeChild(newDiv);

4. Replace an Element

Call replaceChild on the parent element.

var anotherDiv = document.createElement('div');
anotherDiv.innerText = 'Replacement content';
container.replaceChild(anotherDiv, newDiv);

🎨 Updating Element Styles

Styles define how a page looks, much like clothing defines an outfit. DOM manipulation can update an element’s styling too.

1. Update the style Property Directly

var box = document.getElementById('box');
box.style.backgroundColor = 'lightblue';
box.style.width = '200px';
box.style.height = '100px';

2. Add and Remove Classes to Control Styles

Use className or classList to add and remove class names.

box.classList.add('active');
box.classList.remove('active');
Managing styles through classes keeps the styling in CSS, making it easier to maintain.

💡 Combining Events and DOM Manipulation

DOM manipulation often works with events, such as changing content when a button is clicked.

Example: Toggle text visibility on a button click

<button id="btn">Toggle visibility</button>
<div id="text">This text can be shown or hidden</div>

JavaScript:

var btn = document.getElementById('btn');
var text = document.getElementById('text');

btn.onclick = function () {
    if (text.style.display === 'none') {
        text.style.display = 'block';
    } else {
        text.style.display = 'none';
    }
};
Assigning onclick sets the button’s click handler. The function runs each time the button is clicked.

❓ Knowledge Check

Q1: What is the DOM?

The DOM is the Document Object Model: a tree representation of page content that JavaScript can manipulate to change the page.

Q2: How do you find page elements with JavaScript?

Use getElementById, getElementsByTagName, getElementsByClassName, querySelector, or querySelectorAll.

Q3: How do you add new content to an element?

Create an element with createElement, then add it to a parent on the page with appendChild.


🧪 Exercises

Exercise 1: Add a Red Box Containing Text When a Button Is Clicked

<button id="addBtn">Add a box</button>
<div id="container"></div>

<style>
    .red-box {
        width: 100px;
        height: 50px;
        background-color: red;
        color: white;
        margin: 5px 0;
        line-height: 50px;
        text-align: center;
    }
</style>

<script>
    var addBtn = document.getElementById('addBtn');
    var container = document.getElementById('container');

    addBtn.onclick = function () {
        // Create a new box and append it to container here
    };
</script>

Exercise 2: Change a Paragraph’s Text Color When It Is Clicked

<p id="para">Click me to change my color</p>

<style>
    .color-change {
        color: green;
    }
</style>

<script>
    var para = document.getElementById('para');

    // Add a click handler to para that toggles the color-change class
</script>

🎉 You now understand the DOM tree, selecting and manipulating nodes, and updating page content and styles dynamically. Keep practicing these front-end foundations to build richer page interactions!