简体   繁体   English

如何使用Javascript获取所有孩子(即孩子的孩子)?

[英]How do i get all children (ie children of children) with Javascript?

I need a javascript function or a CSS Selector (or even a ProtoypeJS function) which gets me ALL elements (ie. descendants) under a particular element. 我需要一个javascript函数或一个CSS Selector(甚至一个ProtoypeJS函数),它可以获取特定元素下的所有元素(即后代)。

I understand there are CSS selectors such as : 'p, a, div' , which would get me all the elements of those three types. 我知道有一些CSS选择器,例如: 'p,a,div' ,这将获得这三种类型的所有元素。 However I need to get EVERYTHING without specifying type. 但是我需要在没有指定类型的情况下获得所有内容。

ie. 即。 I want something like 我想要类似的东西

myElement.getElements('*')

You can use querySelectorAll 您可以使用querySelectorAll

myElement.querySelectorAll('*')

Note: Supported in IE8+ 注意: IE8 +支持

Compatible with all versions of IE, not just IE8+... 兼容IE的所有版本,而不仅仅是IE8 + ......

myElement.getElementsByTagName("*")

* is treated as a special case for getElementsByTagName to return all descendants regardless of tag name. *被视为getElementsByTagName的特殊情况,无论标记名称如何,都返回所有后代。 (This is different to querySelectorAll , where * is a genuine selector that matches all elements) (这与querySelectorAll不同,其中*是匹配所有元素的真正选择器)

The method that will get you all child elements as an extended PrototypeJS array is childElements() http://api.prototypejs.org/dom/Element/prototype/childElements/ 将所有子元素作为扩展PrototypeJS数组的方法是childElements() http://api.prototypejs.org/dom/Element/prototype/childElements/

element.childElements()

For other situations you might want to narrow down the child elements that are returned you can use select() 对于其他情况,您可能希望缩小返回的子元素,您可以使用select()

element.select('div')

will return all the div children of element 将返回element所有div子element

It's easy enough to do this with CSS alone. 仅使用CSS就可以轻松完成此操作。 The * (universal) selector targets all elements. * (通用)选择器以所有元素为目标。 If you want to target all children of a specific element , then you can simply do this: 如果您想要定位特定element所有子element ,那么您可以简单地执行此操作:

element * {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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