DOM Manipulation in JavaScript

The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. JavaScript is the primary language used to interact with and manipulate the DOM, allowing for dynamic and interactive web pages.

On This Page

Accessing DOM Elements

You can select elements from the DOM using various methods provided by the document object.

Common Methods:

Example: Getting an Element by ID

Let's say you have an element like this:

<div id="myDiv">Hello, World!</div>

You can access it in JavaScript like so:


const myDivElement = document.getElementById('myDiv');
console.log(myDivElement.textContent); // Outputs: "Hello, World!"
                

Creating and Appending Elements

JavaScript allows you to create new HTML elements dynamically and add them to the DOM.

Key Methods:

Example: Creating and Appending a Paragraph

Adding a new paragraph to a container.

Click the button above to see it in action!

Modifying Element Content and Attributes

You can easily change the text, HTML content, and attributes of existing DOM elements.

Useful Properties and Methods:

Example: Changing Text and an Attribute

Initial Text

Placeholder Image

Click the button to see the text and image update.

Styling Elements

JavaScript provides powerful ways to manipulate the style of elements, either directly or by toggling CSS classes.

Methods:

Example: Inline Styling vs. Class Toggling

This text will be styled.

Click the button to apply both inline styles and class-based styles.

Removing Elements

You can remove elements from the DOM when they are no longer needed.

Methods:

Example: Removing an Element

This paragraph will be removed.

Click the button to remove the paragraph above.

Event Handling

DOM manipulation is often triggered by user interactions, such as clicks, mouse movements, or keyboard input. Event handling allows you to respond to these events.

Common Event Listeners:

Methods for Adding Listeners:

Example: Click Event Listener

No interaction yet.

Interact with the button above to see event handling in action.