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. [Link]("id") - Gets one element by ID.
2. [Link]("class") - Gets all elements with that class.
3. [Link]("tag") - Gets all elements by tag.
4. [Link]("selector") - Gets the first match by CSS selector.
5. [Link]("selector") - Gets all matches by CSS selector.
3. Changing Elements
You can change HTML content, attributes, and style using the DOM:
- textContent: Change text
[Link] = "New text";
- innerHTML: Change inner HTML
[Link] = "<b>Bold</b>";
- style: Change CSS styles
[Link] = "red";
- setAttribute(): Change attributes
[Link]("class", "newClass");
4. Creating and Removing Elements
To add elements:
let newElem = [Link]("p");
[Link] = "I'm new!";
[Link](newElem);
To remove elements:
[Link](existingElem);
5. DOM Events
JavaScript HTML DOM - Full Guide
You can react to user actions using events:
- [Link]("click", function() {...})
- [Link]("mouseover", function() {...})
- [Link]("change", function() {...})
Example:
[Link]("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
- [Link](tag)
- [Link](text)
- [Link](child)
- [Link](child)
- [Link](new, old)
- [Link](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