The DOM (Document Object Model) allows you to interact with and manipulate HTML elements using JavaScript. In this post, we’ll cover the basics:
Selecting elements
Creating elements
Updating elements
Removing elements
- Selecting Elements
JavaScript provides multiple ways to select elements from the DOM:
// By ID
let title = document.getElementById('main-title');
// By class
let items = document.getElementsByClassName('item');
// By tag name
let paragraphs = document.getElementsByTagName('p');
// Modern way (CSS selector) [TBD]
let firstItem = document.querySelector('.item'); // Selects the first match
let allItems = document.querySelectorAll('.item'); // Selects all matches
2. Updating Elements
You can update the content, attributes, or style of any element.
let title = document.getElementById('main-title');
// Change text
title.innerHtml = "Updated Title";
// Change style
title.style.color = "blue";
3. Creating Elements
You can dynamically create new HTML elements and add them to the page.
// Create a new paragraph
const newPara = document.createElement('p');
newPara.innerText = "This is a new paragraph";
// Append it to the body or another element
document.body.appendChild(newPara);
4. Removing Elements
To remove an element from the DOM:
const element = document.getElementById('remove-me');
element.remove(); // Modern and simple
Top comments (0)