jquery match multiple data groups (only if they are all true)

Viewed 70

I have data groups on elements

data-foo
data-bar

I'd like to have a jquery selector that selects items where foo and bar BOTH match, e.g.

$("[data-foo='blah'],[data-bar='quax']")

would select the elements where data-foo = 'blah' and data-bar='quax'

It seems right now I'm getting results where data-foo=blah OR data-bar=quax. I need this to be data-foo=blah AND data-bar=quax

2 Answers

Just take out the comma. In essence, that is an OR selector. Without the comma, it looks for both.

console.log($("[data-foo='blah'],[data-bar='quax']").length) // 3 = not what you want 
console.log($("[data-foo='blah'][data-bar='quax']").length) // 1 = what you want
console.log($("[data-foo='blah'][data-bar='quax']").html()) // Just to make sure its the right one
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div data-foo="blah" data-bar="quax">Both</div>
<div data-foo="blah">Foo</div>
<div data-bar="quax">Bar</div>

Another possible solution is to use filter:

$("[data-foo='blah']").filter("[data-bar='quax']")

However, this isn't terribly efficient, compared to @jamiec's answer which uses a single selector.

Related