A DOM Element represents an HTML element (like <div>, <p>, <h1>) in the browser’s Document Object Model (DOM). JavaScript lets you find these elements, read their content, and change their text, HTML, styles, attributes, and classes at runtime.
innerHTML, textContent, style, classList, and attributes.querySelector / querySelectorAll for flexibility with CSS selectors.You can access elements in several ways:
document.getElementById("id") – returns the element with the specified id.document.getElementsByClassName("class") – returns a live HTMLCollection of elements with that class.document.getElementsByTagName("tag") – returns a live HTMLCollection of elements with that tag name.document.querySelector("selector") – returns the first element matching a CSS selector.document.querySelectorAll("selector") – returns a static NodeList of all elements matching the selector.
// Access elements
const header = document.getElementById("header");
const items = document.getElementsByClassName("item");
const divs = document.getElementsByTagName("div");
const firstButton = document.querySelector("button");
const allButtons = document.querySelectorAll("button");
Commonly used properties and methods include:
element.innerHTML – get or set the HTML content inside the element.element.textContent – get or set the plain text inside the element.element.style – access or change inline CSS styles (e.g. element.style.color = "red").element.classList – add, remove, or toggle CSS classes.element.setAttribute(name, value) – set an attribute on the element.element.getAttribute(name) – read the value of an attribute.
// Change content and style
const box = document.querySelector(".box");
box.innerHTML = "<strong>Bold Text</strong>";
box.style.color = "red";
box.classList.add("highlight");
box.setAttribute("data-id", "123");
console.log(box.getAttribute("data-id"));
Here is a simple example that updates the text and style of a <div> using JavaScript.
<div id="message">Hello</div>
const msg = document.getElementById("message");
msg.textContent = "Hello, DOM!";
msg.style.fontWeight = "bold";
msg.style.color = "green";
When the JavaScript runs:
id="message" is selected.textContent changes from Hello to Hello, DOM!.fontWeight is set to bold, and color is set to green.Click the button to change the text and style of the box using DOM element methods.
textContent when you want only text (safer for user input or plain text).innerHTML only when you intentionally insert HTML markup.innerHTML – it can cause XSS (security issues).classList is the cleanest way to add, remove, or toggle CSS classes.getElementsByClassName and getElementsByTagName return live collections that update as the DOM changes.Array.from(...)) if you want to use methods like forEach.textContent and innerHTML.classList.add(), classList.remove(), and classList.toggle().data-* attributes) using setAttribute and getAttribute.