Skip to main content Accessibility Feedback

Traversing the DOM

Element.children

Returns a live HTMLCollection, which means if items are added to it later, the collection updates as well.

<div class="wizards">
	<ul>
		<li>Gandalf</li>
		<li>Radagast</li>
		<li>Hermione</li>
		<li>Neville</li>
	</ul>
</div>
let wizards = document.querySelector('.wizards');
let wizardsList = document.querySelector('.wizards ul');

// returns an HTMLCollection with the ul element
let wizardDescendants = wizards.children;

// returns an HTMLCollection with the list items
let wizardListDescendants = wizardsList.children;

// Add a new item
let li = document.createElement('li');
li.textContent = 'Merlin';
wizardsList.append(li);

// wizardListDescendants now automatically contains the new li

Preorder my new course on Web Components! Want to learn how to build Web Components from scratch, master best practices, and more? Preorder today and get $100 off of the launch price.


Find this useful? You can support my work by purchasing an annual membership.