Чем является childnodes в elem childnodes
Перейти к содержимому

Чем является childnodes в elem childnodes

  • автор:

What is the difference between children and childNodes in JavaScript?

I have found myself using JavaScript and I ran across childNodes and children properties. I am wondering what the difference between them is. Also is one preferred to the other?

asked Oct 28, 2011 at 22:55
13.4k 7 7 gold badges 52 52 silver badges 103 103 bronze badges

3 Answers 3

Understand that .children is a property of an Element. 1 Only Elements have .children , and these children are all of type Element. 2

However, .childNodes is a property of Node. .childNodes can contain any node. 3

A concrete example would be:

let el = document.createElement("div"); el.textContent = "foo"; el.childNodes.length === 1; // Contains a Text node child. el.children.length === 0; // No Element children. 

Most of the time, you want to use .children because generally you don’t want to loop over Text or Comment nodes in your DOM manipulation.

If you do want to manipulate Text nodes, you probably want .textContent or .nodeValue instead. 4

It’s important to understand the distinction between the 2, before deciding which one to use: The .textContent property represents the text content of the node and its descendants whereas the .nodeValue property represents the value of the current node.

1. Technically, it is an attribute of ParentNode, a mixin included by Element.
2. They are all elements because .children is a HTMLCollection, which can only contain elements.
3. Similarly, .childNodes can hold any node because it is a NodeList.
4. Or .innerText . See the differences here or here.

4,938 3 3 gold badges 17 17 silver badges 27 27 bronze badges
answered Oct 28, 2011 at 22:59
168k 57 57 gold badges 354 354 silver badges 397 397 bronze badges
Yeah, IE seems to have some problems: quirksmode.org/dom/w3c_core.html#t71
Oct 28, 2011 at 23:12

Actually, children is a property of the parentnode interface, not element. usonsci.wordpress.com/2014/09/30/html-children-vs-childnodes

Sep 30, 2014 at 13:37
Seems iOS 8.3 (maybe others?) doesn’t support .children on XML documents: jsfiddle.net/fbwbjvch/1
May 21, 2015 at 10:12

Only had trouble with this on Microsoft Edge with XML nodes. It appears Microsoft Edge doesn’t like children. That’s good, I wouldn’t want that browser reproducing.

Nov 21, 2016 at 2:57
Natural follow-up of «element vs. node»: stackoverflow.com/questions/132564/…
Jan 27, 2017 at 16:30

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

I believe childNodes is more reliable. For example, MDC (linked above) notes that IE only got children right in IE 9. childNodes provides less room for error by browser implementors.

125k 58 58 gold badges 324 324 silver badges 410 410 bronze badges
answered Oct 28, 2011 at 22:59
Matthew Flaschen Matthew Flaschen
282k 50 50 gold badges 516 516 silver badges 543 543 bronze badges
Darn, if only this worked on IE 6-8, it would be a dream come true.
Oct 28, 2011 at 23:05

@minitech it does work (for some value of work). Apparently .children doesn’t filter out comment nodes, but it filters out text nodes.

Oct 28, 2011 at 23:16
@Raynos: Exactly — same with .getElementsByTagName(‘*’) . IE can be so annoying sometimes.
Oct 28, 2011 at 23:17
There are shim/polyfill implementations of children that support IE.
Jan 28, 2018 at 7:45

Good answers so far, I want to only add that you could check the type of a node using nodeType :

This will give you an integer: (taken from here)

| Value | Constant | Description | | |-------|----------------------------------|---------------------------------------------------------------|--| | 1 | Node.ELEMENT_NODE | An Element node such as 

or . | | | 2 | Node.ATTRIBUTE_NODE | An Attribute of an Element. The element attributes | | | | | are no longer implementing the Node interface in | | | | | DOM4 specification. | | | 3 | Node.TEXT_NODE | The actual Text of Element or Attr. | | | 4 | Node.CDATA_SECTION_NODE | A CDATASection. | | | 5 | Node.ENTITY_REFERENCE_NODE | An XML Entity Reference node. Removed in DOM4 specification. | | | 6 | Node.ENTITY_NODE | An XML node. Removed in DOM4 specification. | | | 7 | Node.PROCESSING_INSTRUCTION_NODE | A ProcessingInstruction of an XML document | | | | | such as declaration. | | | 8 | Node.COMMENT_NODE | A Comment node. | | | 9 | Node.DOCUMENT_NODE | A Document node. | | | 10 | Node.DOCUMENT_TYPE_NODE | A DocumentType node e.g. for HTML5 documents. | | | 11 | Node.DOCUMENT_FRAGMENT_NODE | A DocumentFragment node. | | | 12 | Node.NOTATION_NODE | An XML node. Removed in DOM4 specification. | |

Note that according to Mozilla:

The following constants have been deprecated and should not be used anymore: Node.ATTRIBUTE_NODE, Node.ENTITY_REFERENCE_NODE, Node.ENTITY_NODE, Node.NOTATION_NODE

elem.getBoundingClientRect() broken on mobile screen

I’m developing a website using gatsby.js and it involves a slide-in animation as you scroll down. I wrote code that worked perfectly until I opened dev tools and tried it using the device toolbar. here’s a reproduction demo as well as a webpage to make it easier https://getboundingclientrect-is-broken.netlify.app

 .slideFR < width: 100px; height: 100px; background-color: #957b26; position: relative; left: 450px; transform: translateX(1000px); >.slideFL < width: 100px; height: 100px; background-color: #26958f; position: relative; left: 300px; transform: translateX(-1000px); >.inSight < transition: all 0.5s; transform: translateX(0); >.space
let elemsFL = document.getElementsByClassName("slideFL"); var leftiesLoaded = Array.from( < length: elemsFL.length >, (_, i) => false ); // creates array length of elemsFL full of let elemsFR = document.getElementsByClassName("slideFR"); var rightersLoaded = Array.from( < length: elemsFR.length >, (_, i) => false ); // creates array length of elemsFR full of document.addEventListener("scroll", function (event) < let windowHeight = window.outerHeight; console.log( "%c/* ----------- scroll ---------- */", "color: purple; font-weight: bold" ); checkIfInSight(elemsFL, leftiesLoaded, windowHeight); checkIfInSight(elemsFR, rightersLoaded, windowHeight); >); /* -------------------------------- touchmove ------------------------------- */ document.addEventListener("touchmove", function (event) < let windowHeight = window.outerHeight; console.log( "%c/* ---------- touchmove --------- */", "color: red; font-weight: bold" ); checkIfInSight(elemsFL, leftiesLoaded, windowHeight); checkIfInSight(elemsFR, rightersLoaded, windowHeight); >); function checkIfInSight(elemArray, boolArray, windowHeight) < for (let counter = 0; counter < elemArray.length; counter++) < const elem = elemArray[counter]; let elemRect = elem.getBoundingClientRect(); let elemPosTop = elemRect.top; let elemPosBottom = elemPosTop + elem.scrollHeight; if (elemPosTop = 0) < if (!boolArray[counter]) < console.log( "%c In Sight", "color: green", elem.classList[0] ); boolArray[counter] = true; elem.classList.add("inSight"); >else < console.log( "%c In Sight And Loaded", "color: yellow", elem.classList[0] ); >> else < console.log( elem.classList[0], "\tOut Of Sight", elemPosTop, "=0\t\t\t", elem.offsetTop ); boolArray[counter] = false; elem.classList.remove("inSight"); > > > 

Edit: As I’m troubleshooting this I replaced elem.offsetTop with window.scrollY which indeed made me realize that for some reason the it is not interpreting the scroll action as actually scrolling for quite a while. I still don’t know what I’m doing wrong or what the issue is

HTML DOM Element childNodes

The childNodes property returns a collection (list) of an elements’s child nodes.

The childNodes property returns a NodeList object.

The childNodes property is read-only.

childNodes[0] is the same as firstChild .

Important!

childNodes returns nodes: Element nodes, text nodes, and comment nodes.

Whitespace between elements are also text nodes.

Alternative:

The children property returns elements (ignores text and comments).

See Also:

Node Properties

HTML Nodes vs Elements

In the HTML DOM (Document Object Model), an HTML document is a collection of nodes with (or without) child nodes.

Nodes are element nodes, text nodes, and comment nodes.

Whitespace between elements are also text nodes.

Elements are only element nodes.

childNodes vs children

childNodes returns child nodes (element nodes, text nodes, and comment nodes).

children returns child elements (not text and comment nodes).

Siblings vs Element Siblings

Siblings are «brothers» and «sisters».

Siblings are nodes with the same parent (in the same childNodes list).

Element Siblings are elements with the same parent (in the same children list).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *