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.