scriptkiddie scriptkiddie - 6 months ago 14
Javascript Question

Jquery: select an element when two or more conditions are true

I have an element like this

<ul>
<li data-ud="321" data-id="42">
<li data-ud="322" data-id="42">
<li data-ud="323" data-id="42">
<li data-ud="324" data-id="42">

<li data-ud="321" data-id="43">
<li data-ud="322" data-id="43">
<li data-ud="323" data-id="43">
<li data-ud="324" data-id="43">

<li data-ud="321" data-id="44">
<li data-ud="322" data-id="44">
<li data-ud="323" data-id="44">
<li data-ud="324" data-id="44">

<li data-ud="321" data-id="45">
<li data-ud="322" data-id="45">
<li data-ud="323" data-id="45">
<li data-ud="324" data-id="45">

</ul>


Now I want to select a element with data-id=45 and data-ud=322. I have tried but it didn't work.

Thanks in advance

Answer

To use 'and' in a selector, simply don't use any other separator, eg a li and class myclass would be:

li.myclass

to find by attribute, use [attribute=x], so to combine the two:

li[data-id=45][data-ud=322]

or, with jquery:

$("li[data-id=45][data-ud=322]")

This can be difficult to read and prone to errors eg a space between the two [][] will give a totally different result, so you can instead use filter to the same effect:

$("li").filter("[data-id=45]").filter("[data-ud=322]")

Fiddle example: https://jsfiddle.net/o9fdhphf/

Comments