Search code examples
javascripthtmlchildren

Plain JavaScript: Getting children of body returns undefined


I'm trying to get all child elements of the <body> element, but it's not working. For some reason, it always returns undefined.

I have found similar questions on StackOverflow, but all of them have much longer code. I'm hoping that this simple question can get a simple answer.

JSFiddle link: https://jsfiddle.net/mkeacdsw/10

HTML:

<body>
<div>
</div>
</body>

JavaScript:

console.log("Below here");
console.log(document.getElementsByTagName("body"));
console.log(document.getElementsByTagName("body").children);
console.log("Above here");

If you open the browser console, you will see this:

undefined console output

As you can see, it successfully gets the <body> element, but not its children.

What in the world is going on? How do I get all of the children of <body>? I already tried replacing children with childNodes and it still doesn't work.


Solution

  • document.getElementsByTagName returns a collection, not a DOM Element, which is where the children attribute resides.

    You want

    console.log(document.getElementsByTagName("body")[0].children);