Sunday, 5 December 2010

Search elements with custom attributes

Lately someone on asp.net forums wanted help for searching elements with custom attributes
just incase you have similar requirement -
<script type="text/javascript">
       $(document).ready(function () {
           var searchText = "a";  //change this as per required
           String.prototype.startsWith = function (str) {
               return (this.match("^" + str) == str)
           }
           var divs = $("div").filter(function () {
               var elem = $(this);
               var validElem = false;
               $(elem.get(0).attributes).each(function () {
                   var node = this.nodeName;
                   if (node.startsWith(searchText) == true) {
                       validElem = true;
                       return false;
                   }
               });
               return validElem;
           });   
 //now  following will return you number of divs having custom attributes starting with "a"       
 var length = divs.length;        
 });
   </script>

No comments:

Post a Comment