Daniel Matthew

Finding Child Elements In JavaScript

There are several techniques that allow us to discover if a particular DOM element has any children - whether there are any nodes contained within.

Warning: Nodes are usually, but not always HTML elements: the text inside a list element, for example.

if (element.firstChild) {
	// It has at least one

if (element.hasChildNodes()) {
	// Element has at least one

if (element.childNodes.length) {
	// Again, has at least one...


var box = document.getElementById('box'); console.log(box.firstChild); // Returns NodeList console.log(box.hasChildNodes()); // Returns true console.log(box.childNodes) // Returns array

Daniel is a front-end developer at Talis, with an interest in accessibility, performance, and web components.