user3875080
user3875080

Reputation: 71

querySelectorAll() exclude attribute and children of that attribute

I've got a element tree that looks like.

<div>
  <div required>
    <div content></div>
  </div>
  <div>
    <div content></div>
  </div>
</div>

How can I do a querySelector on the root div that gets all elements tagged as "content" without getting any that are below a parent element with the "required" attribute? I'm thinking something like.

querySelectorAll('[content]:not([required]')

But that query would fetch all elements tagged as content and not tagged as required rather than all elements tagged as content that aren't below a required element.

Upvotes: 3

Views: 4250

Answers (2)

Miaplacidus
Miaplacidus

Reputation: 545

Repl Example

JS

const query = document.querySelectorAll('div :not([required]) [content]')
query.forEach((element) => {
  console.log(element.innerHTML)
})

HTML

<div>
  <div required>
    <div content>NO</div>
  </div>
  <div>
    <div content>YES</div>
    <div>
      <div content>YES</div>
    </div>
  </div>
</div>

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 370979

Unfortunately, :not only accepts a simple selector, so :not([required] [content]) to match a [content] which is not a child of [content] won't work. You'll have to programmatically filter the elements after selecting them:

const notRequiredContents = [...document.querySelectorAll('[content]')]
  .filter(elm => !elm.closest('[required]'));
console.log(notRequiredContents);
<div>
  <div required>
    <div content></div>
  </div>
  <div>
    <div content></div>
  </div>
</div>

It'd be theoretically possible to do this with only a query string by chaining :not([required]) with the descendant selector, but it looks really ugly and repetitive and shouldn't be done:

const notRequiredContents = document.querySelectorAll(`
  body > :not([required]) > [content],
  body > :not([required]) > :not([required]) > [content],
  body > :not([required]) > :not([required]) > :not([required]) > [content],
  body > :not([required]) > :not([required]) > :not([required]) > :not([required]) > [content]
`);
// continue above pattern for as much nesting as may exist
console.log(notRequiredContents[0], notRequiredContents.length);
<div>
  <div required>
    <div content>a</div>
  </div>
  <div>
    <div content>b</div>
  </div>
</div>

Upvotes: 3

Related Questions