iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

DOM Elements

Every HTML tag becomes an Element instance in the DOM. They share a common interface plus tag-specific extras (an HTMLInputElement knows about value; an HTMLImageElement knows about src).

Universal Element properties

PropertyWhat it gives
tagNameUppercase tag name, e.g. "DIV".
id / className / classListid / class string / class API.
textContentConcatenated text of the element.
innerHTML / outerHTMLHTML inside / including the element.
attributesNamedNodeMap of attribute objects.
datasetAuto-object for data-* attributes.
styleInline style declarations.
parentElementParent (or null at the root).
childrenHTMLCollection of element children.
firstElementChild / lastElementChildEdge children.

Attributes vs. properties

JS
<input id="name" value="Ada">

// Attribute — what was in the HTML
input.getAttribute("value");      // "Ada"

// Property — current state
input.value;                      // "Ada", changes as the user types

// Common pairs that differ:
//   class    ↔ className / classList
//   for      ↔ htmlFor
//   checked  ↔ defaultChecked (attr) vs checked (property = live state)

classList — the modern class API

JS
el.classList.add("active");
el.classList.remove("loading");
el.classList.toggle("dark", isDark);     // pass a boolean for force-on/off
el.classList.replace("old", "new");
el.classList.contains("active");
Tip: Reach for dataset to read/write data-* attributes — el.dataset.userId is much cleaner than el.getAttribute("data-user-id").

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from DOM Elements!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Add the "active" class to an element using the modern API.

el. .add('active');

Test yourself

Q1. Read data-user-id with…
Q2. Toggle a class conditionally with…
Q3. The attribute the HTML had vs. the live state…

Discussion

Loading…