根据GENERIC属性值查找对象

时间:2013-05-31 18:20:24

标签: jquery selector

如何根据属性值选择对象。

HTML:

<li abc='dog'>a</li>
<a def='cat'>b</a>
<span ghi='cat'>c</span>
<b jkl='dog'>d</b>
<u mno='dog'>e</u>
<div pqr='cow'>f</div>

JS:

var listofdog = $("[?='dog']"); //find anything with attribute value = dog

3 个答案:

答案 0 :(得分:0)

您必须获取所有属性的数组,并迭代它们。

var elem = document.getElementsByTagName('*');
for(var j = 0; j < elem.length; j++) {

   var attr = elem[j].attributes;

   for(var i = 0; i < attr.length; i++) {
       if(attr[i].value == 'dog') 
           // do something with elem[j]
   }

}

答案 1 :(得分:0)

这是你可以做的事情:

function findElementsByAttributeValue(attrValue) {
    return $('*').filter(function (_) {
        var hasAttr = false;
        $(this.attributes).each(function (_, _) {
            return !(hasAttr = this.nodeValue === attrValue);
        });
        return hasAttr;
    });
}

尝试:

console.log(findElementsByAttributeValue('dog').length); // outputs 3

jsFiddle here

答案 2 :(得分:0)

此代码基于@Barmar评论。尚未测试。 投票,如果工作。

var value_to_find = "dog";
$("*").filter(function(){
    function has_attr_value(obj, value){
        var listofattr = $(obj).attributes;
        if (listofattr.length > 0){
             var has_attr = false;
             $.each(listofattr,function(){
                  if (this.value == value){
                      has_attr = true;
                      return;
                  }
             });
             return has_attr;
        }
        else{
            return false;
        }
    }

    return has_attr_value(this,value_to_find);
});
相关问题