JavaScript HTML DOM Elements
14 April 2025 | Category: JavaScript
The HTML DOM Elements are the actual HTML tags you see in a webpage like <div>
, <p>
, <h1>
, <a>
, etc. Using JavaScript, you can access, modify, create, or remove these elements dynamically to make your webpage interactive.
đź§ What Are DOM Elements?
In the DOM (Document Object Model), each HTML tag becomes a JavaScript object.
For example, this HTML:
<p id="greet">Hello World</p>
Becomes accessible in JavaScript as:
document.getElementById("greet");
That returned object is a DOM Element.
🔍 How to Access DOM Elements
JavaScript provides several methods to select or target elements in the DOM.
âś… 1. getElementById()
const el = document.getElementById("greet");
âś… 2. getElementsByClassName()
const boxes = document.getElementsByClassName("box");
âś… 3. getElementsByTagName()
const paragraphs = document.getElementsByTagName("p");
âś… 4. querySelector()
(CSS Selector)
const main = document.querySelector(".main"); // First element with class 'main'
âś… 5. querySelectorAll()
(Multiple elements)
const allItems = document.querySelectorAll("li.item");
✍️ Modifying DOM Elements
Once you select an element, you can change its content, style, and more.
📝 Change Text
element.textContent = "New Text";
đź’ˇ Change HTML Inside
element.innerHTML = "<strong>Bold text</strong>";
🎨 Change Style
element.style.color = "blue";
element.style.backgroundColor = "#eee";
🏷️ Change Attribute
element.setAttribute("href", "https://example.com");
đź§± Creating and Inserting New Elements
âś… Create a New Element
const newEl = document.createElement("p");
newEl.textContent = "I’m a new paragraph!";
âś… Insert Into Page
document.body.appendChild(newEl); // Adds to the end of body
Or inside another element:
document.getElementById("container").appendChild(newEl);
❌ Removing Elements
âś… Remove directly
element.remove();
đź§“ Old way (for older browsers)
element.parentNode.removeChild(element);
📦 Full Example
<div id="app">
<h1 id="title">Welcome</h1>
<button onclick="changeText()">Click Me</button>
</div>
<script>
function changeText() {
const heading = document.getElementById("title");
heading.textContent = "Thanks for clicking!";
heading.style.color = "green";
}
</script>
🧠Recap – What You Can Do with DOM Elements
âś… Select elements using id
, class
, tag
, or CSS selector
âś… Read or change their text/HTML
âś… Style them with JavaScript
âś… Create, insert, or delete elements
âś… Dynamically update the page content
âś… Conclusion
JavaScript DOM Elements are the heart of any interactive website. By learning how to manipulate them, you gain full control over how your webpage behaves and looks.