Doron Cohen
Doron Cohen

Reputation: 245

get document children with javascript

I'm trying to get document first children (which means: body, html, head etc..) This code line works:

var x = document.body.children;

but this one does not:

var x = document.children;

how can I get the first childs of the document without running on all elements using JAVASCRIPT only?

Upvotes: 2

Views: 5418

Answers (3)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

The document element is appropriately called documentElement. In HTML, this is the <html> tag.

So:

document.documentElement.children

This should give you a list of length 2, with the first being the <head> and the second being the <body>.

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382464

If you use

document.childNodes

you get the docType and the html.

If you use

document.childNodes[1].childNodes

(supposing you have a doctype)

then you get the header and the body.

Upvotes: 1

Ivan Chernykh
Ivan Chernykh

Reputation: 42196

Try childNodes:

document.childNodes

Note that document's children are <DOCTYPE> and <html>

Upvotes: 3

Related Questions