firstChild 和 childNodes[1] 有什么区别?

cow*_*boy 4 javascript

JavaScript DOM 中子节点和子元素有什么区别?

像例如

var myTbodyElement = myTableElement.firstChild;
Run Code Online (Sandbox Code Playgroud)

var mySecondTrElement = myTbodyElement.childNodes[1];
Run Code Online (Sandbox Code Playgroud)

我们可以互换使用第一个子节点和子节点吗?

JLR*_*she 5

.firstChild is equivalent to childNodes[0].

  • firstChild returns the first child node
  • childNodes returns a collection of all child nodes
  • firstElementChild returns the first child element
  • children returns a collection of all child elements

can we substitute using first child and child node

Yes, if you only want to access the first one.

Demo:

var d = document.getElementById('myDiv');

var firstChild = d.firstChild;
var childNodes0 = d.childNodes[0];
var firstElementChild = d.firstElementChild;
var children0 = d.children[0];

console.log("d.childNodes.length is", d.childNodes.length);
console.log("firstChild",             firstChild.nodeName,        firstChild.textContent);
console.log("childNodes[0]",          childNodes0.nodeName,       childNodes0.textContent);
console.log("d.children.length is",   d.children.length);
console.log("firstElementChild",      firstElementChild.nodeName, firstElementChild.textContent);
console.log("children[0]",            children0.nodeName,         children0.textContent);
Run Code Online (Sandbox Code Playgroud)
<div id="myDiv">Some text<b>Some bold text</b>Some more text</div>
Run Code Online (Sandbox Code Playgroud)