DOM in JavaScript Detailed
DOM in JavaScript Detailed
The DOM (Document Object Model) is a programming interface for HTML and XML documents. It
represents the page so that programs can change the document structure, style, and content. The
Example HTML:
<html>
<head><title>My Page</title></head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>
DOM Tree:
Document
html
head
title
body
h1
Node Types:
|---------------|--------------------|--------|
| Element | Node.ELEMENT_NODE | 1 |
| Text | Node.TEXT_NODE |3 |
| Comment | Node.COMMENT_NODE | 8 |
3. Accessing Elements
- document.getElementById("id")
- document.getElementsByClassName("class")
- document.getElementsByTagName("tag")
- document.querySelector("selector")
- document.querySelectorAll("selector")
Example:
- Changing Content:
document.getElementById("link").href = "https://www.example.com";
- Changing Styles:
document.getElementById("box").style.backgroundColor = "blue";
- Creating Elements:
document.body.appendChild(newDiv);
- Removing Elements:
element.parentNode.removeChild(element);
6. Event Handling
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
Common Events:
7. DOM Traversal
- element.parentNode
- element.childNodes
- element.firstChild
- element.lastChild
- element.nextSibling
- element.previousSibling
Example:
8. Real-World Example
<script>
document.getElementById("changeColor").addEventListener("click", function() {
document.body.style.backgroundColor = "lightgreen";
});
</script>
JavaScript uses the DOM API to interact with the document. Any changes made to the DOM using
10. Summary
| Feature | Purpose |
|--------------------|---------------------------------------------------|