0

how to select object base on attribute value.

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
printf
  • 110
  • 1
  • 8
  • 2
    I don't think there's anything built-in to do this. What kind of crazy design requires it? – Barmar May 31 '13 at 18:22
  • 3
    To do it you can use `$("*").filter(...)`, where the filter function enumerates all the attributes and checks whether any of them is `dog`. – Barmar May 31 '13 at 18:23
  • See http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery to list all attributes. – Barmar May 31 '13 at 18:26
  • thanx Barmar. i can use $("*").filter – printf May 31 '13 at 18:36

3 Answers3

0

You must get an array of all attributes, and iterate them.

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]
   }

}
Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44
  • 1
    This only operates on a single element, it doesn't find all elements that match the criteria. – Barmar May 31 '13 at 18:43
0

Here's something you can do:

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

Try:

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

jsFiddle here.

acdcjunior
  • 132,397
  • 37
  • 331
  • 304
0

this code base on @Barmar comment. not yet test. vote if working.

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);
});
printf
  • 110
  • 1
  • 8