Document.children VS document.childNodes

The Document interface inherits the Node interface and indicates Node.childNodes . It works great, but what are children ? There is no such attribute in the specifications.

They work differently. If we have a <!doctype html> node, document.childNodes contains it, but document.children does not.

+5
source share
1 answer

From Matthew Flashen answer :

Element.children returns only the children, and Node.childNodes returns all the children of the node. Note that elements are nodes, so both are available on elements.

<!doctype html> is a node is a DOM tree, so it is specified in childNodes , but it is a DocumentType node, not an Element , so it does not appear in children .

The reason you did not find children in the specification you were looking at is probably because it is relatively new - it was added to DOM4 (which became the W3C Recommendation only in 2015).

If you need to go through the Element in the DOM tree (ignoring other types of node - for example, text nodes), you will find children and the associated APIs (first / lastElementChild, previous / nextElementSibling) more but since they are newer, older browsers do not support these APIs completely, so you should refer to compatibility tables and / or use polyfill.

+2
source

All Articles