Mark As Completed Discussion

DOM Manipulation

Manipulating the DOM (Document Object Model) using JavaScript is a powerful technique that allows you to interact with web pages and dynamically modify their contents. With DOM manipulation, you can change the appearance, structure, and behavior of HTML elements.

JavaScript provides a wide range of methods and properties that enable you to manipulate the DOM. Let's explore some common DOM manipulation techniques:

Selecting Elements

To manipulate an element in the DOM, you first need to select it. JavaScript provides several methods to select elements based on different criteria, such as their CSS class, HTML tag name, or unique identifier.

Here's an example of selecting an element by its id:

JAVASCRIPT
1const element = document.getElementById('elementId');

Modifying Element Properties

Once you have selected an element, you can modify its properties, such as changing its text content, attribute values, or styling.

Here's an example of changing the color of a header element:

JAVASCRIPT
1const header = document.getElementById('header');
2header.style.color = 'blue';

Creating and Appending Elements

You can also create new elements dynamically and append them to the DOM. This is useful when you want to add or insert elements programmatically.

Here's an example of creating a new paragraph element and appending it to the body of the document:

JAVASCRIPT
1const paragraph = document.createElement('p');
2paragraph.textContent = 'This is a new paragraph.';
3document.body.appendChild(paragraph);

DOM manipulation in JavaScript opens up endless possibilities for creating interactive and dynamic web pages. By understanding the different methods and properties available, you can effectively manipulate the DOM and enhance the user experience on your websites.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment