使用纯 javascript 获取 body 标签中的所有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12823264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 08:34:44  来源:igfitidea点击:

Get all elements in the body tag using pure javascript

javascripthtml

提问by Kaiusee

I'm trying to get all the elements (tags) inside the Body tag of an HTML page in an array using pure javascript. I mean without using any framework (ex. JQuery).

我正在尝试使用纯 javascript 获取数组中 HTML 页面的 Body 标记内的所有元素(标记)。我的意思是不使用任何框架(例如 JQuery)。

I've found that you can use document.allbut that will return all the elements inside the whole document including the scripts.

我发现您可以使用,document.all但这将返回整个文档中的所有元素,包括脚本。

Is there anyway I can get those tags?

无论如何我可以获得这些标签吗?

thanks

谢谢

回答by jfriend00

If you want all elements inside the body tag, not just first level children, you can simply use getElementsByTagName()with a wildcard:

如果您想要 body 标签内的所有元素,而不仅仅是一级子元素,您可以简单地使用getElementsByTagName()通配符:

var elems = document.body.getElementsByTagName("*");

回答by Sirko

You can use document.querySelectorAll()for that.

你可以用document.querySelectorAll()它。

If you really want all (including nested tags), use this

如果你真的想要所有(包括嵌套标签),使用这个

 var elements = document.querySelectorAll( 'body *' );

If you only want the immediate child nodes, use

如果您只想要直接子节点,请使用

 var elements = document.querySelectorAll( 'body > *' );