To get the children of an element, you use the childNodes
property of the element.
The following selects the children of the element whose id is container
:
const container = document.querySelector('#container');
const children = container.childNodes;
Code language: JavaScript (javascript)
How it works:
- First, select the element whose id is container using the
querySelector()
method. - Then, use the
childNodes
property to get the children of the container elements.
To get the first and last children, you use the firstChild
and lastChild
properties as follows:
const container = document.querySelector('#container');
const firstChild = container.firstChild,
lastChild = container.lastChild;
Code language: JavaScript (javascript)
Was this tutorial helpful ?