Abishek
Abishek

Reputation: 11691

Searching html elements based on data attributes

Is there a way to search elements based on data attributes?

I have the following code and would like to know how can this be achieved

<UL>
    <LI data-relation_id=1/>
    <LI data-relation_id=1/>
    <LI data-relation_id=1/>
    <LI data-relation_id=2/>
    <LI data-relation_id=2/>
    <LI data-relation_id=2/>
    <LI data-relation_id=3/>
    <LI data-relation_id=3/>
    <LI data-relation_id=3/>
</UL>

On a click event I basically want to find out all the items that belong to a specific data-relation?

function getRelatedObjects(relationId){
   //Search all the li's and get the LI 
   //that have the data-relation_id== relationId

}

Can this be done using jquery?

Upvotes: 1

Views: 705

Answers (2)

Paul
Paul

Reputation: 141829

You can't search by associated data specifically, but if the data is set by attribute then you can search using the attribute selector:

function getRelatedObjects(relationId){
   return $('li[data-relation_id="'+relationId+'"]');
}

JSFiddle

Upvotes: 0

IOrlandoni
IOrlandoni

Reputation: 1828

The data attribute is just an attribute, so you can use the attribute selector.

$('li[data-relation_id='+relationId+']')

Upvotes: 5

Related Questions