简体   繁体   中英

How to recursively select all children under an element Javascript

I need a function that recursively selects all child elements but wont select elements (and those elements children) if they have the "foo" attribute.

<section>
  <div>
   <span foo>
    <input>
   </span>
  </div>
  <p>
    <img>
  </p>
</section>
//should return [section, div, p, img]

I need raw Javascript please

edit: I tried something like this:

$tag.querySelectorAll(":not([foo])")

but querySelectorAll(":not([foo])") will still return the children of the unselected element.

You can use element.querySelectorAll() with the :not modifier here, together with the [attr] selector:

var nonFooElements = parentElement.querySelectorAll("*:not([foo])");

Be aware that this sort of call will be moderately expensive because the selector doesn't begin with an id or a classname, so don't do huge amounts of it.

I adapted this answer from this one: https://stackoverflow.com/a/21975970/5009210

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