'querySelectorAll with multiple conditions
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?
Solution 1:[1]
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");
source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:
https://api.jquery.com/multiple-attribute-selector/
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.
Solution 2:[2]
With pure JavaScript you can do this (such as SQL) and anything you need, basically:
<html>
<body>
<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">
<br/>
<br/>
<button onclick="myFunction()">Try it</button>
<script>
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');
window.document.body.appendChild(node);
});
}
</script>
</body>
</html>
Solution 3:[3]
Yes, querySelectorAll does take a group of selectors:
form, p, legend
Solution 4:[4]
Using just document.querySelectorAll('selector1, selector2, selector3') didn't work for me, had to use forEach() method alongside to achieve the desired result.
document.querySelectorAll('selector1, selector2, selector3').forEach(item => {
item.//code
})
document.querySelectorAll('#id1, #id2, #id3').style = 'background-color: red';
document.querySelectorAll('#id4, #id5, #id6').forEach(item => {
item.style = 'background-color: red';
})
<div id="id1">id1</div>
<div id="id2">id2</div>
<div id="id3">id3</div>
<div id="id4">id4</div>
<div id="id5">id5</div>
<div id="id6">id6</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | double-beep |
| Solution 3 | Bergi |
| Solution 4 | first user |
