简体   繁体   中英

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 ?

Try childNodes :

document.childNodes

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

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> .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM