JavaScript HTML DOM - Full Guide
1. What is the DOM?
DOM stands for Document Object Model. It's a tree-like structure created by the browser from an HTML page.
Each HTML element becomes an object that JavaScript can interact with.
Think of it like a family tree:
- The <html> is the root.
- <head> and <body> are children of <html>.
- Every element inside <body> is also a node in this tree.
JavaScript can use the DOM to read, change, add, or remove HTML elements.
2. Accessing Elements
You can get elements in the DOM using several methods:
1. document.getElementById("id") - Gets one element by ID.
2. document.getElementsByClassName("class") - Gets all elements with that class.
3. document.getElementsByTagName("tag") - Gets all elements by tag.
4. document.querySelector("selector") - Gets the first match by CSS selector.
5. document.querySelectorAll("selector") - Gets all matches by CSS selector.
3. Changing Elements
You can change HTML content, attributes, and style using the DOM:
- textContent: Change text
element.textContent = "New text";
- innerHTML: Change inner HTML
element.innerHTML = "<b>Bold</b>";
- style: Change CSS styles
element.style.color = "red";
- setAttribute(): Change attributes
element.setAttribute("class", "newClass");
4. Creating and Removing Elements
To add elements:
let newElem = document.createElement("p");
newElem.textContent = "I'm new!";
document.body.appendChild(newElem);
To remove elements:
document.body.removeChild(existingElem);
5. DOM Events
JavaScript HTML DOM - Full Guide
You can react to user actions using events:
- element.addEventListener("click", function() {...})
- element.addEventListener("mouseover", function() {...})
- element.addEventListener("change", function() {...})
Example:
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
6. DOM Tree Navigation
You can move around the DOM like this:
- parentNode: Go to the parent
- childNodes / children: Get all children
- firstChild / firstElementChild
- lastChild / lastElementChild
- nextSibling / nextElementSibling
- previousSibling / previousElementSibling
7. Useful DOM Methods
- document.createElement(tag)
- document.createTextNode(text)
- element.appendChild(child)
- element.removeChild(child)
- element.replaceChild(new, old)
- element.cloneNode(true or false)
8. DOM Best Practices
- Use IDs for unique elements
- Use classes for multiple elements
- Cache elements in variables to improve performance
- Avoid excessive DOM manipulation in loops
- Clean up event listeners when not needed