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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
Good answers so far, I want to only add that you could check the type of a node using
nodeType
:yourElement.nodeType
This will give you an integer: (taken from here)
Note that according to Mozilla:
Element.children
returns only element children, whileNode.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 gotchildren
right in IE 9.childNodes
provides less room for error by browser implementors..children
is a property of an Element. Only Elements have children, and these children are all of type Element.However
.childNodes
is a property of Node..childNodes
can contain any node.So a concrete example would be
Of course
.children
is DOM4 so browser support is shaky, however if you use the DOM-shim, your cross browser problems will go away!Most of the time you want to use
.children
because generally you don't want to loop over TextNodes or Comments in your DOM manipulation.If you do want to manipulate TextNodes you probably want
.textContent
instead.