DOM Manipulation
DOM (Document Object Model) manipulation is a critical skill in web development. It allows you to dynamically change the content, structure, and style of a webpage using JavaScript. Understanding how to interact with the DOM is essential for creating interactive and dynamic web applications.
1. Understanding the DOM
The DOM is a hierarchical representation of the HTML document. It consists of nodes and objects representing elements, attributes, and text in the document. JavaScript can access and manipulate the DOM to update the webpage dynamically.
Example of an HTML structure:
2. Selecting Elements
To manipulate the DOM, you first need to select the elements you want to change. You can use various methods to select elements in the DOM.
getElementById: Selects an element by its ID.
getElementsByClassName: Selects elements by their class name.
getElementsByTagName: Selects elements by their tag name.
querySelector: Selects the first element that matches a CSS selector.
querySelectorAll: Selects all elements that match a CSS selector.
Example:
3. Changing Content
You can change the content of elements using properties like innerHTML
, textContent
, and innerText
.
innerHTML: Sets or returns the HTML content of an element.
textContent: Sets or returns the text content of an element.
innerText: Similar to
textContent
, but also respects CSS styling (e.g.,display: none
).
Example:
4. Modifying Styles
You can change the styles of elements using the style
property.
Example:
5. Creating and Removing Elements
You can create new elements and add them to the DOM, or remove existing elements.
Example:
6. Event Listeners
You can attach event listeners to elements to respond to user actions like clicks, key presses, and mouse movements.
Example:
In this example, clicking the button will change the header text and add a new item to the list.
7. Use Case project - a Todo-List:
Suppose you're building a simple to-do list application. You want to allow users to add new items to the list and remove items.
HTML:
JavaScript:
In this example:
We select the input, button, and list elements.
We add an event listener to the button that creates a new list item with the input text when clicked.
Each new item includes a "Remove" button that, when clicked, removes the item from the list.
This use case demonstrates how to dynamically manipulate the DOM to create interactive web applications. Understanding DOM manipulation is essential for building responsive and user-friendly web interfaces. As you progress, you'll learn more advanced techniques and best practices for working with the DOM effectively.
Help us improve the content 🤩
You can leave comments here.
Last updated