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

1

22

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).

Higdon answered 11/4, 2016 at 9:35 Comment(4)
Can you put logical operators on CSS selectors?Praedial
document.querySelectorAll("p div, p span")Sexlimited
@RayonDabre That is wrong. That will select span elements inside p and all div elements throughout the DOM.Sexlimited
@RajaprabhuAravindasamy, Agreed!Mahalia
S
48

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"
Sharma answered 11/4, 2016 at 9:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.