This is not a problem, I just ask for the easiest way to implement this.
What I have.
In HTML: list of checkboxes.
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
In JavaScript — array of several values: var aValues = [1, 3]; And I need fetch all checkboxes from DOM with values specified in aValues.
How did I do this:
var aoNodes = document.querySelectorAll('input[value="1"], input[value="3"]');
But maybe anybody know easier (shorter) way to build the query, something like: input[value="1"|"3"] or input[value="1", "3"].
Both examples above are incorrect, but I gave them just to be more clear with you.
UPDATE
More things to clarify my question:
- jQuery can’t be used in my case
- We use ExtJS in our project.
Your
querySelectorAll('input[value="1"], input[value="3"]')is probably the briefest, even CSS3 doesn’t have an attribute selector for “any of these values”. (Neither does jQuery.) You can build the big selector fromaValuesfairly easily usingArray#join:Fairly concise though sadly repeats bits and pieces. You could use a reusable function:
Then:
If you don’t like the
joinapproach, you could get all relevantinputelements and then filter out the ones whose values are not in the array:That might be slower than building the big selector for
querySelectorAllsince you’re filtering in the JavaScript layer rather than the browser’s selector engine, but unless you’re doing this repeatedly in a tight loop, it’s not likely to matter. Also, note that I’ve relied onArray#indexOf, which isn’t supported by quite as many browsers asquerySelectorAll(IE8 has the latter, for instance, but not the former).Speaking of which: I’m guessing you know that not all browsers support
querySelectorAllyet, although wow it’s getting close, looks like nearly everything but IE6 and IE7. I assume if you’re using it, you know that your target environment will have it.For the jQuery folks: That filtering gets (much) more concise using jQuery:
Nice and concise. Again, possibly a bit slower than doing it all in
querySelectorAll, and again unlikely to matter.Update: You’ve said you’re using ExtJS on this project. According to the
DomQuerydocs, it doesn’t offer a selector that does what you want either. It does offerfilterwhich could be useful if you want to do the filter-after-the-fact approach, but I frankly think thejoinapproach listed at the very top is going to be the most concise and best performing.