Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I select elements on multiple attribute values

Tags:

jquery

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)?

like image 547
user380719 Avatar asked Nov 08 '11 01:11

user380719


People also ask

How do you select an element by its attributes?

The [attribute|="value"] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-). Note: The value has to be a whole word, either alone, like class="top", or followed by a hyphen( - ), like class="top-text".

Can you have multiple data attributes?

A data attribute is a custom attribute that stores information. Data attributes always start with “data-” then followed with a descriptive name of the data that is being stored. You can have multiple data attributes on an element and be used on any HTML element.


2 Answers

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

like image 98
Dmitry B. Avatar answered Sep 22 '22 18:09

Dmitry B.


You could for example chain and filter like so

var elements = $('div[attr1="value1"]').filter('div[attr2="value2"]'); 
like image 41
SunnyRed Avatar answered Sep 24 '22 18:09

SunnyRed