Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between firstChild and childNodes[1]?

Tags:

javascript

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?

like image 714
cowboy Avatar asked Oct 17 '25 08:10

cowboy


1 Answers

.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);
<div id="myDiv">Some text<b>Some bold text</b>Some more text</div>
like image 168
JLRishe Avatar answered Oct 19 '25 21:10

JLRishe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!