0

I am selecting a div with container class. But If I want to find the child nodes of this element, it says undefined.

let targetNode=document.getElementsByClassName('container')
console.log(targetNode.childNodes)
<div class="container">
 <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Repellat, assumenda.</p>
 </div>
Ishan Ahmed
  • 105
  • 11
  • `document.getElementsByClassName('container')[0]` since [`getElementsByClassName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) returns a `HTMLCollection`. – Lain Jan 13 '21 at 10:29

2 Answers2

1

document.document.getElementsByClassName('container') will return a collection of HTMLElements. So all you have to do is specify which element you want to access with an index like this:

var children = document.getElementsByClassName('container');
var child;
if (children != undefined && children.length > 0) {
  for (var i = 0 ; i < children.length; i++) {
    console.log(document.getElementsByClassName('container')[i])
  }
}

Cheers

SpaceNinjaApe
  • 312
  • 1
  • 13
0

let targetNode=document.getElementsByClassName('container')
console.log(targetNode[0].childNodes)
<div class="container">
 <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Repellat, assumenda.</p>
 </div>
Amit Saini
  • 575
  • 4
  • 11