What is the difference between child node and child element in JavaScript DOM?
like e.g.
var myTbodyElement = myTableElement.firstChild;
and
var mySecondTrElement = myTbodyElement.childNodes[1];
Can we use first child and child node interchangeably?
.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);
<div id="myDiv">Some text<b>Some bold text</b>Some more text</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With