20

Let's say I want to find all div elements and span inside p.

Is it possible to get all what I want in a single querySelectorAll invocation?

Conceptually it should be something like document.querySelectorAll("div | p span") (where | means or).

victor.ja
  • 811
  • 1
  • 7
  • 27
Just a learner
  • 26,690
  • 50
  • 155
  • 234

1 Answers1

44

Yes. You can use the same logical operators allowed in CSS:

OR: chain selectors with commas

document.querySelectorAll('div, p span');
// selects divs, and spans in ps

AND: chain selectors without whitespace

document.querySelectorAll('div.myClass');
// selects divs with the class "myClass"

NOT: :not()-selector

document.querySelectorAll('div:not(.myClass)');
// selects divs that do not have the class "myClass"
KWeiss
  • 2,954
  • 3
  • 21
  • 37