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)
| Property | Returns |
|---|---|
parentElement | The element above, or null at the root. |
children | Live HTMLCollection of element children. |
childElementCount | How many element children. |
firstElementChild / lastElementChild | Edge children. |
previousElementSibling / nextElementSibling | Adjacent elements. |
Node-aware navigation (includes text and comments)
| Property | Returns |
|---|---|
parentNode | Parent, or null. |
childNodes | Live NodeList of every child node. |
firstChild / lastChild | Edge child nodes (may be text). |
previousSibling / nextSibling | Adjacent nodes (may be text). |
ownerDocument | The 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');
Seven letters.
Discussion
Loading…