简体   繁体   中英

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.

I understand there are CSS selectors such as : 'p, a, div' , which would get me all the elements of those three types. However I need to get EVERYTHING without specifying type.

ie. I want something like

myElement.getElements('*')

You can use querySelectorAll

myElement.querySelectorAll('*')

Note: Supported in IE8+

Compatible with all versions of IE, not just IE8+...

myElement.getElementsByTagName("*")

* is treated as a special case for getElementsByTagName to return all descendants regardless of tag name. (This is different to querySelectorAll , where * is a genuine selector that matches all elements)

The method that will get you all child elements as an extended PrototypeJS array is 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()

element.select('div')

will return all the div children of element

It's easy enough to do this with CSS alone. The * (universal) selector targets all elements. If you want to target all children of a specific element , then you can simply do this:

element * {}

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