In jQuery, there are two methods you can use to get an element's children. The contents()
method will get all child nodes including comment and text nodes. The children()
method will only get children that are HTML elements. Here's how to do this in vanilla JS with browser support back to IE9.
For the examples in this post, assume the following HTML. I've deliberately added a comment and some liberal spacing:
<ul id="rainbow">
<!-- Colours of the rainbow -->
<li>Red</li>
<li>Orange</li>
<li>Yellow</li>
<li>Green</li>
<li>Blue</li>
<li>Indigo</li>
<li>Violet</li>
</ul>
Get all child nodes
To get all child nodes of an element, including comment and text nodes, you can use the Node.childNodes
property:
// Get the #rainbow element
var rainbow = document.querySelector("#rainbow");
// Save its childNodes property to a variable
var coloursOfRainbow = rainbow.childNodes;
// NodeList(17) [ #text, <!-- Colours of the rainbow -->, #text, li, #text, li, #text, li, #text, li, … ]
console.log(coloursOfRainbow);
This property is supported back to IE5.
Get HTML children only
To only get children that are HTML elements, you can use the ParentNode.children
property:
// Get the #rainbow element
var rainbow = document.querySelector("#rainbow");
// Save its children property to a variable
var coloursOfRainbow = rainbow.children;
// HTMLCollection { 0: li, 1: li, 2: li, 3: li, 4: li, 5: li, 6: li, length: 7 }
console.log(coloursOfRainbow);
This property is supported back to IE9.
Converting into true arrays
The childNodes
property contains a NodeList
while the children
property contains an HTMLCollection
.
It's usually a good idea to convert these into true arrays before trying to manipulate them. All of the following will work:
// (Also works for rainbow.children)
var coloursOfRainbow = rainbow.childNodes;
// The most well-supported method
coloursOfRainbow = Array.prototype.slice.call(coloursOfRainbow);
// ES6 only (CAN be polyfilled)
coloursOfRainbow = Array.from(coloursOfRainbow);
// ES6 only (CANNOT be polyfilled)
coloursOfRainbow = [...coloursOfRainbow];
Learn more:
Array.prototype.slice.call()
Array.from()
- Polyfill for
Array.from()
- Spread syntax (
...
) - What can and can't be polyfilled in vanilla JS?
Summary
- Use the
Node.childNodes
property to get all of an element's children. - Use the
ParentNode.children
property to only get HTML children.