Can I put logical operators in document.querySelectorAll? If so, how?

10,762

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"
Share:
10,762

Related videos on Youtube

Just a learner
Author by

Just a learner

Updated on September 15, 2022

Comments

  • Just a learner
    Just a learner over 1 year

    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") (if | means or).

    • Ismael Miguel
      Ismael Miguel about 8 years
      Can you put logical operators on CSS selectors?
  • Jose Rui Santos
    Jose Rui Santos about 8 years
    You made a typo on the last one. Should be document.querySelectorAll('div:not(.myClass)');