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:
Get all child nodes
To get all child nodes of an element, including comment and text nodes, you can use the
This property is supported back to IE5.
Get HTML children only
To only get children that are HTML elements, you can use the
This property is supported back to IE9.
Converting into true arrays
childNodes property contains a
NodeList while the
children property contains an
It’s usually a good idea to convert these into true arrays before trying to manipulate them. All of the following will work:
- Polyfill for
- Spread syntax (
- What can and can’t be polyfilled in vanilla JS?
- Use the
Node.childNodesproperty to get all of an element’s children.
- Use the
ParentNode.childrenproperty to only get HTML children.
If you have questions, feedback, or any other suggestions, please do email me. I'd love to hear from you!