Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 429
Just a learner Avatar asked Apr 11 '16 09:04

Just a learner


People also ask

What does the querySelectorAll () method do?

The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.

What is the difference between document querySelector and document querySelectorAll?

document. querySelector(selectors); It returns the first element which matches the selector. querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s).

What kind of selectors does querySelector and querySelectorAll take as arguments?

querySelector() , document. querySelectorAll( ), Element. closest() , and Element. matches() methods all accept CSS selectors are their argument.


1 Answers

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"
like image 199
KWeiss Avatar answered Oct 10 '22 05:10

KWeiss