JavaScript DOM 中子节点和子元素有什么区别?
像例如
var myTbodyElement = myTableElement.firstChild;
Run Code Online (Sandbox Code Playgroud)
和
var mySecondTrElement = myTbodyElement.childNodes[1];
Run Code Online (Sandbox Code Playgroud)
我们可以互换使用第一个子节点和子节点吗?
.firstChild is equivalent to childNodes[0].
firstChild returns the first child nodechildNodes returns a collection of all child nodesfirstElementChild returns the first child elementchildren returns a collection of all child elementscan 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)