EN ES
Home > Web development > Javascript Tutorials > How to Manipulate the DOM (Document Object Model) with JavaScript

How to Manipulate the DOM (Document Object Model) with JavaScript

Diego Cortés
Diego Cortés
September 30, 2024
How to Manipulate the DOM (Document Object Model) with JavaScript

DOM (Document Object Model) manipulation is one of the most fundamental skills for any web developer using JavaScript. This article will guide you through the basics of how to interact with and modify the DOM using JavaScript. You will learn about the various methods, properties, and events that you can use to make your web pages dynamic and interactive.

What is the DOM?

The DOM (Document Object Model) is a structural representation of an HTML or XML document. It is a programming interface that allows scripts (such as JavaScript) to access and modify the content, structure, and style of documents. Each element in an HTML file is converted into an object that can be manipulated.

Features of the DOM

  • Hierarchical Structure: The DOM organizes the elements of a document into a tree structure, where each node in the tree represents an object of the document.
  • Interactivity: It allows developers to modify the content and structure of the page in response to events or user actions.
  • Compatibility: The DOM is compatible with multiple programming languages, although JavaScript is the most commonly used in the browser.

How to Access the DOM

Selecting Elements

To manipulate the DOM, you first need to access the elements you want to modify. There are several methods to select elements in the DOM:

getElementById

This method returns a single element that has the specified ID.

const element = document.getElementById('my-id');

getElementsByClassName

This method returns a collection of all elements that have a given class.

const elements = document.getElementsByClassName('my-class');

getElementsByTagName

This method returns all elements in the document that match the specified tag name.

const elements = document.getElementsByTagName('div');

querySelector

This method returns the first element that matches the specified CSS selector.

const element = document.querySelector('.my-class');

querySelectorAll

This method returns all elements that match the specified CSS selector.

const elements = document.querySelectorAll('div.my-class');

Manipulating DOM Elements

Once you have accessed an element, you can modify its content and attributes.

Changing an Element's Content

Use the innerHTML or textContent property to change an element's content.

const element = document.getElementById('my-id');
element.innerHTML = 'New content'; // Changes the HTML content
element.textContent = 'Plain text'; // Changes only the text

Changing Attributes

You can use the setAttribute method to change an element's attributes.

const element = document.getElementById('my-id');
element.setAttribute('src', 'new-image.jpg');

Style and Classes

You can modify an element's style using the style property or change its classes using classList.

const element = document.getElementById('my-id');
element.style.color = 'red'; // Changes the text color
element.classList.add('new-class'); // Adds a new class

Adding and Removing Elements

In addition to modifying existing elements, you can also create new elements and remove them from the DOM.

Creating a New Element

Use document.createElement to create a new element and appendChild to add it to an existing element.

const newElement = document.createElement('div');
newElement.textContent = 'This is a new div';
document.body.appendChild(newElement);

Removing an Element

To remove an element from the DOM, use the remove or removeChild method.

const element = document.getElementById('my-id');
element.remove(); // Removes the element

// Or, if you need to remove a child
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.removeChild(child);

Events in the DOM

DOM manipulation is also closely related to event handling. Events are actions that occur on the page and can be captured and handled with JavaScript.

Listening to Events

Use addEventListener to listen for events on an element.

const button = document.getElementById('my-button');
button.addEventListener('click', () => {
    alert('Button clicked');
});

Types of Events

Some of the most common types of events are:

  • click: Fired when an element is clicked.
  • mouseover: Fired when a mouse pointer is over an element.
  • keypress: Fired when a key is pressed.

Complete Example

Here’s a complete example showing how to manipulate the DOM using the concepts described above.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DOM Example</title>
</head>
<body>
    <div id="my-id">Original text</div>
    <button id="my-button">Change text</button>

    <script>
        const button = document.getElementById('my-button');
        button.addEventListener('click', () => {
            const element = document.getElementById('my-id');
            element.textContent = 'Text changed';
        });
    </script>
</body>
</html>

Conclusion

Manipulating the DOM with JavaScript allows you to create dynamic and responsive web applications. This article has provided you with a foundation on how to access, modify, and manage elements in the DOM. By practicing and experimenting with these techniques, you will improve your skills in building interactive and engaging user interfaces.

Remember that practice is essential. Start exploring and manipulating the DOM today!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 40.79 ms