How do I select elements on multiple attribute values

Jquery

Jquery Problem Overview


With jQuery, it is easy to select elements with a given attribute value.

For example:

var elements = $('div[attr1="value1"]');

But how do I select on multiple attributes (e.g., attr1 = value1 and attr2 = value2)?

Jquery Solutions


Solution 1 - Jquery

Since jquery uses CSS selectors, as defined by the CSS specification a selector with multiple conditions will look like:

$('div[attr1="value1"][attr2="value2"]')

see the CSS spec for further reference: http://www.w3.org/TR/CSS2/selector.html#matching-attrs

Solution 2 - Jquery

You could for example chain and filter like so

var elements = $('div[attr1="value1"]').filter('div[attr2="value2"]');

Solution 3 - Jquery

Find this solution quite simple.

$('[attr1="home"][attr2="settings"]')

Solution 4 - Jquery

To select multiple attributes, see the code below.

This code will find all inputs that have an id attribute and whose name attribute ends with 'man' and sets the value.

$( "input[id][name$='man']" ).val( "this input has id and name ends with 'man'" );

Solution 5 - Jquery

You can even target an element like so:

const elem = $('.className[type="checkbox"][name="someName"]')

or in more dynamic way with a parameter:

const elem = $('.elemClassName_'+$(this).data('id')+'[type="checkbox"][name="someName"]')

I use the last example to target a checkbox when an input value changes. The above is from many examples, and they work for me.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser380719View Question on Stackoverflow
Solution 1 - JqueryDmitry B.View Answer on Stackoverflow
Solution 2 - JquerySunnyRedView Answer on Stackoverflow
Solution 3 - JqueryBalasubramani MView Answer on Stackoverflow
Solution 4 - JqueryVISHNUView Answer on Stackoverflow
Solution 5 - JqueryStrabekView Answer on Stackoverflow