Dom Elements in JavaScript
? DOM Elements in JavaScript
What are DOM Elements?
A DOM Element represents an HTML tag (like
<div>,<p>,<button>, etc.) in the Document Object Model.Elements have properties (like
id,className,innerHTML) and methods (likeappendChild(),remove(),setAttribute()) to interact with them.Elements are the main building blocks of the webpage content you manipulate with JavaScript.
How to Access DOM Elements?
1. By ID
const elem = document.getElementById("myElement");2. By Class Name
const elems = document.getElementsByClassName("myClass"); // Returns HTMLCollection3. By Tag Name
const elems = document.getElementsByTagName("p"); // Returns HTMLCollection4. By CSS Selectors
const elem = document.querySelector(".myClass"); // First matching elementconst elems = document.querySelectorAll(".myClass"); // NodeList of all matching elementsCommon DOM Element Properties
| Property | Description | Example |
|---|---|---|
id | Element's ID | elem.id = "header" |
className | Space-separated class names | elem.className = "active" |
innerHTML | HTML content inside the element | elem.innerHTML = "<b>Hi</b>" |
textContent | Text content inside the element | elem.textContent = "Hello" |
style | Inline CSS styles | elem.style.color = "red" |
attributes | Collection of attributes | elem.getAttribute("href") |
Common DOM Element Methods
| Method | Description | Example |
|---|---|---|
appendChild(node) | Adds a child node | elem.appendChild(newNode) |
remove() | Removes the element from the DOM | elem.remove() |
setAttribute(name, val) | Sets an attribute | elem.setAttribute("src", "img.jpg") |
getAttribute(name) | Gets the value of an attribute | elem.getAttribute("alt") |
classList.add(class) | Adds a CSS class | elem.classList.add("visible") |
classList.remove(class) | Removes a CSS class | elem.classList.remove("hidden") |
Example: Creating and Adding a New Element
const newDiv = document.createElement("div");newDiv.textContent = "Hello World!";newDiv.classList.add("greeting");document.body.appendChild(newDiv);Example: Changing Element Content and Style
const header = document.querySelector("h1");header.textContent = "Welcome!";header.style.color = "green";Summary
DOM Elements are JavaScript objects representing HTML tags.
You can select, modify, add, and remove elements using DOM properties and methods.
DOM manipulation is core to dynamic, interactive web pages.
Want to explore event handling on DOM elements or traversing between elements (parent, children, siblings)?