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

DOM Navigation

From any node you can walk the DOM tree in every direction. There are two families of properties: node-aware (includes text and comments) and element-aware (skips them).

Element-aware navigation (the everyday choice)

PropertyReturns
parentElementThe element above, or null at the root.
childrenLive HTMLCollection of element children.
childElementCountHow many element children.
firstElementChild / lastElementChildEdge children.
previousElementSibling / nextElementSiblingAdjacent elements.

Node-aware navigation (includes text and comments)

PropertyReturns
parentNodeParent, or null.
childNodesLive NodeList of every child node.
firstChild / lastChildEdge child nodes (may be text).
previousSibling / nextSiblingAdjacent nodes (may be text).
ownerDocumentThe document the node lives in.

Search up & down with a selector

JS
// Up — nearest matching ancestor (or self)
const item = el.closest("[data-id]");

// Down — first matching descendant
const link = el.querySelector("a");

// Down — all matching
const inputs = form.querySelectorAll("input");
Tip: Reach for element-aware navigation by default. parentNode and firstChild regularly trip people up by returning text nodes that look "invisible" in the markup.

Example

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

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

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

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

Exercise

Walk up to the nearest matching ancestor.

const card = el. ('.card');

Test yourself

Q1. Element-aware sibling property is…
Q2. Nearest matching ancestor (or self) is…
Q3. `firstChild` may surprise you because it…

Discussion

Loading…