Accessing First and Last Children in the DOM
You'll learn: How to quickly access the first and last children of an element, and why the difference between "child" and "element child" matters.
Why Two Sets of Properties?
When navigating the DOM, you often need to grab the first or last child of an element. JavaScript gives you two pairs of properties for this:
firstChild/lastChild— return the first/last node (including text nodes and comments)firstElementChild/lastElementChild— return the first/last element node only
The Critical Distinction
Remember from earlier lessons that the DOM contains different node types. firstChild might return a text node containing whitespace between tags, while firstElementChild skips over text and comment nodes to find the first actual HTML element.
const container = document.getElementById('nav');
// Returns the first node (might be whitespace!)
const firstNode = container.firstChild;
// Returns the first element <a>, <div>, etc.
const firstEl = container.firstElementChild;
// Same pattern for last children
const lastNode = container.lastChild;
const lastEl = container.lastElementChild;
Think of It Like This
Imagine a bookshelf (the parent element) with books and bookmarks (elements) plus random scraps of paper (text nodes). firstChild grabs whatever is at the front — might be a scrap of paper. firstElementChild reaches past the scraps to grab the first actual book.
When to Use Which
Use the "element" versions (firstElementChild, lastElementChild) in almost all cases when building interfaces — they ignore whitespace and give you predictable element references. Use the plain versions only when you specifically need to work with text nodes.
Key Takeaway: firstElementChild and lastElementChild return the first and last element children, skipping text and comment nodes, making them far more reliable than their plain counterparts for most DOM manipulation tasks.