javascript – querySelectorAll with multiple conditions-ThrowExceptions

Exception or error:

Is it possible to make a search by querySelectorAll using multiple unrelated conditions? If yes how? And how to specify whether those are AND or OR criteria?

For example:

How to find all forms, ps and legends with a single querySelectorAll call? Possible?

How to solve:

Is it possible to make a search by querySelectorAll using multiple unrelated conditions?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:

var list = document.querySelectorAll("form, p, legend");

…will return a list containing any element that is a form or p or legend.

CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:

var list = document.querySelectorAll("");

…will return a list of all div elements that also (and) have the class foo, ignoring other div elements.

You can, of course, combine them:

var list = document.querySelectorAll(",, div legend");

…which means “Include any div element that also has the foo class, any p element that also has the bar class, and any legend element that’s also inside a div.”


According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical ‘OR’.

This example returns a list of all div elements within the document
with a class of either “note” or “alert”:

var matches = document.querySelectorAll("div.note, div.alert");


Meanwhile to get the ‘AND’ functionality you can for example simply use a multiattribute selector, as jquery says:

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it’s as obvious as “.class1.class2” to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated ‘OR’ and ‘AND’ expressions.


Yes, querySelectorAll does take a group of selectors:

form, p, legend


With pure JavaScript you can do this (such as SQL) and anything you need, basically:



<input type='button' value='F3' class="c2" id="btn_1">
<input type='button' value='F3' class="c3" id="btn_2">
<input type='button' value='F1' class="c2" id="btn_3">

<input type='submit' value='F2' class="c1" id="btn_4">
<input type='submit' value='F1' class="c3" id="btn_5">
<input type='submit' value='F2' class="c1" id="btn_6">


<button onclick="myFunction()">Try it</button>

    function myFunction() 
        var arrFiltered = document.querySelectorAll('input[value=F2][type=submit][class=c1]');

            arrFiltered.forEach(function (el)
                var node = document.createElement("p");
                node.innerHTML = el.getAttribute('id');




Leave a Reply

Your email address will not be published. Required fields are marked *