Day thirteen in javascript .I shared the topics,what I learn today.
Dom
in javascript:
DOM
stands for Document Object Model.
It is a programming interface that represents the structure of an HTML (or XML) document as a tree of objects.
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<p class="text">This is a paragraph.</p>
<button id="btn">Click Me</button>
</body>
</html>
DOM tree
Document
└── html
├── head
│ └── title
│ └── "My Page"
└── body
├── h1#heading
│ └── "Hello World"
├── p.text
│ └── "This is a paragraph."
└── button#btn
└── "Click Me"
Accessing the DOM with JavaScript
JavaScript provides methods to access and manipulate DOM elements
// By ID
let heading = document.getElementById("heading");
// By class
let para = document.getElementsByClassName("text");
// By tag
let buttons = document.getElementsByTagName("button");
// Modern way - query selectors
let heading2 = document.querySelector("#heading"); // ID
let para2 = document.querySelector(".text"); // Class
Changing Content
document.getElementById("heading").textContent = "Welcome to DOM!";
document.querySelector(".text").innerHTML = "This text is <b>updated</b>.";
Changing Styles
document.getElementById("heading").style.color = "blue";
document.querySelector(".text").style.fontSize = "20px";
Adding and Removing Elements
// Create element
let newDiv = document.createElement("div");
newDiv.textContent = "I am a new div!";
document.body.appendChild(newDiv); // Add to body
// Remove element
let btn = document.getElementById("btn");
btn.remove();
Adding Event Listeners
let button = document.getElementById("btn");
button.addEventListener("click", function() {
alert("Button clicked!");
});
Eg:
<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>
<h1 id="heading">Hello World</h1>
<p class="text">This is a paragraph.</p>
<button id="btn">Click Me</button>
<script>
// Change heading text
document.getElementById("heading").textContent = "Welcome to DOM!";
// Change style
document.querySelector(".text").style.color = "green";
// Add new element
let newPara = document.createElement("p");
newPara.textContent = "I am a new paragraph.";
document.body.appendChild(newPara);
// Add event listener
document.getElementById("btn").addEventListener("click", function() {
alert("You clicked the button!");
});
</script>
</body>
</html>
Happy coding...
Top comments (0)