When building dynamic web applications, interactive elements are everything. Whether it’s updating a user dashboard, validating a form, or opening a modal, DOM Manipulation is the bridge between static HTML/CSS and interactive JavaScript.
In this guide, we’ll break down how to select elements, update their content, and handle user events with clean JavaScript.
- What is the DOM?
The "Document Object Model"(DOM) is a programming interface for web documents. It represents the structure of your HTML document as a tree of nodes, allowing JavaScript to read, edit, add, or delete elements dynamically.
- Selecting Elements from the DOM
Before modifying an element, you need to find it. Modern JavaScript gives us two primary methods:
i. .querySelector(): Selects the "first" element that matches a CSS selector.
ii. querySelectorAll(): Selects "all" matching elements and returns a NodeList.
Example:
--> Select by ID
const mainHeading = document.querySelector('#heading');
--> Select by class
const primaryButton = document.querySelector('.btn-primary');
--> Select all list items
const navLinks = document.querySelectorAll('.nav-link');
- Changing Content and Styles: Once you've selected an element, you can modify its text, HTML structure, or inline CSS styles directly. -->Updating Text Content Use .textContent to update text safely without rendering HTML tags.Example:
const heading = document.querySelector('h1');
heading.textContent = 'Welcome back, User!';
In this example we stored the h1 in a variable heading, then changed its text content to'Welcome back, User!' using ".text content"
-->Modifying Styles
You can access the .style property to change dynamic UI state. Example:
const alertBox = document.querySelector('.alert');
alertBox.style.backgroundColor = '#4CAF50';
alertBox.style.display = 'block';
In this example a button given the class attribute 'alert' was targeted with the document.querySelector and was stored in a variable alert.Box then '.style' was used to change its background color.
Key Takeaways
- Use querySelector and querySelectorAll for efficient element selection.
- Rely on .textContent for text updates to keep your DOM updates safe and performant.
"Have questions or want to discuss technical web development content? Feel free to drop a comment or connect with me!"
Top comments (0)