Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.children VS document.childNodes

Interface Document inherits interface Node and specifies Node.childNodes. It works fine, but what is children? There's no such attribute in the specifications.

They work differently. If we have <!doctype html> node, document.childNodes contains it, but document.children doesn't.

like image 315
Iaroslav Baranov Avatar asked Oct 29 '22 21:10

Iaroslav Baranov


1 Answers

From Matthew Flaschen's answer:

Element.children returns only element children, while Node.childNodes returns all node children. Note that elements are nodes, so both are available on elements.

<!doctype html> is a node is a DOM tree, so it is listed in childNodes, but it's a DocumentType node, not an Element, so it doesn't appear in children.

The reason you didn't find children in the spec you were looking at is probably because it's relatively new - it was added in DOM4 (which became a W3C Recommendation only in 2015).

If you need to traverse the Elements in the DOM tree (ignoring other node types -- such as text nodes), you will find children and related APIs (first/lastElementChild, previous/nextElementSibling) more convenient, but since they're newer, the old browsers don't universally support these APIs, so you should consult the compatibility tables and/or use a polyfill.

like image 55
Nickolay Avatar answered Nov 15 '22 07:11

Nickolay