-2

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.

Brayan Byrdsong
  • 145
  • 4
  • 8
  • Im stuck with the not selecting children part, I've tried using querySelectorAll(":not([foo])") but that will still return the elements under the foo. – Brayan Byrdsong Sep 25 '17 at 20:13

1 Answers1

1

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

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20