开发者

Searching html elements based on data attributes

开发者 https://www.devze.com 2023-03-30 14:40 出处:网络
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

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== relati开发者_StackOverflow中文版onId

}

Can this be done using jquery?


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

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消