HTML DOM Element
Working with individual HTML elements using JavaScript
🎯 What are DOM Elements?
DOM elements are individual HTML tags that JavaScript can access, modify, and manipulate. Each HTML tag becomes an element object with properties and methods.
// Find and modify an element
let heading = document.getElementById("myHeading");
heading.innerHTML = "New Text!";
heading.style.color = "blue";
HTML:
New Text!
Finding Elements
By ID
Find element with specific ID
document.getElementById("myId")
By Class
Find elements with specific class
document.getElementsByClassName("myClass")
By Tag
Find elements by tag name
document.getElementsByTagName("p")
By Selector
Find elements using CSS selectors
document.querySelector(".myClass")
🔹 Finding Elements
Different methods to locate HTML elements:
// By ID (returns single element)
let element = document.getElementById("myButton");
// By class name (returns collection)
let elements = document.getElementsByClassName("highlight");
// By tag name (returns collection)
let paragraphs = document.getElementsByTagName("p");
// By CSS selector (returns first match)
let firstDiv = document.querySelector("div");
let specificDiv = document.querySelector("#myId");
let classDiv = document.querySelector(".myClass");
// By CSS selector (returns all matches)
let allDivs = document.querySelectorAll("div");
let allButtons = document.querySelectorAll("button.btn");
// Examples with HTML:
// <div id="container" class="main">
// <p class="text">Paragraph 1</p>
// <p class="text highlight">Paragraph 2</p>
// <button id="myButton">Click me</button>
// </div>
Output:
element: [object HTMLButtonElement]
elements: [object HTMLCollection] (length: 1)
paragraphs: [object HTMLCollection] (length: 2)
firstDiv: [object HTMLDivElement]
allDivs: [object NodeList] (length: 1)
🔹 Changing Element Content
Modify the content of HTML elements:
// Get element
let paragraph = document.getElementById("myParagraph");
// Change text content (plain text only)
paragraph.textContent = "This is plain text";
// Change HTML content (can include HTML tags)
paragraph.innerHTML = "This is <strong>bold</strong> text";
// Change specific attributes
paragraph.setAttribute("class", "newClass");
paragraph.setAttribute("data-info", "some data");
// Get attribute values
let className = paragraph.getAttribute("class");
let dataInfo = paragraph.getAttribute("data-info");
// Direct property access
paragraph.id = "newId";
paragraph.className = "anotherClass";
paragraph.title = "Tooltip text";
console.log(paragraph.textContent); // Plain text content
console.log(paragraph.innerHTML); // HTML content
console.log(paragraph.outerHTML); // Element + content
Output:
This is bold text
This is <strong>bold</strong> text
<p id="newId" class="anotherClass" title="Tooltip text">This is <strong>bold</strong> text</p>
🔹 Changing Element Styles
Modify the appearance of elements using CSS:
let box = document.getElementById("myBox");
// Individual style properties
box.style.color = "red";
box.style.backgroundColor = "yellow";
box.style.fontSize = "20px";
box.style.border = "2px solid blue";
box.style.padding = "10px";
box.style.margin = "5px";
// Multiple styles at once
box.style.cssText = "color: white; background: black; padding: 15px;";
// Add/remove CSS classes
box.classList.add("highlight");
box.classList.remove("old-style");
box.classList.toggle("active"); // Add if not present, remove if present
box.classList.contains("highlight"); // Check if class exists
// Get computed styles (actual applied styles)
let computedStyle = window.getComputedStyle(box);
console.log(computedStyle.color); // Actual color value
console.log(computedStyle.fontSize); // Actual font size
// Hide/show elements
box.style.display = "none"; // Hide element
box.style.display = "block"; // Show element
box.style.visibility = "hidden"; // Hide but keep space
Output:
rgb(255, 255, 255)
20px
🔹 Creating and Removing Elements
Dynamically add and remove HTML elements:
// Create new elements
let newDiv = document.createElement("div");
let newParagraph = document.createElement("p");
let newButton = document.createElement("button");
// Set content and attributes
newDiv.innerHTML = "This is a new div";
newDiv.className = "dynamic-content";
newDiv.id = "newDiv";
newParagraph.textContent = "This is a new paragraph";
newButton.textContent = "Click me";
newButton.onclick = function() { alert("Button clicked!"); };
// Add elements to the page
document.body.appendChild(newDiv); // Add to end of body
newDiv.appendChild(newParagraph); // Add paragraph to div
newDiv.appendChild(newButton); // Add button to div
// Insert at specific position
let container = document.getElementById("container");
container.insertBefore(newDiv, container.firstChild); // Insert at beginning
// Remove elements
let elementToRemove = document.getElementById("oldElement");
if (elementToRemove) {
elementToRemove.parentNode.removeChild(elementToRemove); // Old way
// elementToRemove.remove(); // Modern way
}
// Replace elements
let oldElement = document.getElementById("oldButton");
let newElement = document.createElement("span");
newElement.textContent = "Replaced content";
oldElement.parentNode.replaceChild(newElement, oldElement);
Result:
This is a new paragraph
🔹 Element Properties and Methods
Useful properties and methods for working with elements:
let element = document.getElementById("myElement");
// Element information
console.log(element.tagName); // Tag name (e.g., "DIV")
console.log(element.id); // Element ID
console.log(element.className); // CSS classes
console.log(element.clientWidth); // Width without border
console.log(element.clientHeight); // Height without border
console.log(element.offsetWidth); // Width with border
console.log(element.offsetHeight); // Height with border
// Element relationships
console.log(element.parentNode); // Parent element
console.log(element.children); // Child elements
console.log(element.firstChild); // First child node
console.log(element.lastChild); // Last child node
console.log(element.nextSibling); // Next sibling node
console.log(element.previousSibling); // Previous sibling node
// Element methods
element.focus(); // Give focus to element
element.blur(); // Remove focus from element
element.click(); // Programmatically click element
element.scrollIntoView(); // Scroll element into view
// Check element state
console.log(element.hasAttribute("class")); // Has specific attribute?
console.log(element.hasChildNodes()); // Has child nodes?
Output:
DIV
myElement
container main
300
200
304
204
[object HTMLDivElement]
[object HTMLCollection]
true
true