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
| Property | What it gives |
|---|---|
tagName | Uppercase tag name, e.g. "DIV". |
id / className / classList | id / class string / class API. |
textContent | Concatenated text of the element. |
innerHTML / outerHTML | HTML inside / including the element. |
attributes | NamedNodeMap of attribute objects. |
dataset | Auto-object for data-* attributes. |
style | Inline style declarations. |
parentElement | Parent (or null at the root). |
children | HTMLCollection of element children. |
firstElementChild / lastElementChild | Edge 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');
A property containing class methods.
Discussion
Loading…