Alex Rivera | Logout

How to select elements with event attributes using Jquery?

Asked 2012-10-21T15:48:10.983
9

Hope there's a simple workaround for this. I want to select all the html elements with event attributes. For example: onclick, onkeypress etc. Is there an easiest way to do this using Jquery without selecting by each attribute seperately?

Thanks

Edit
Report

1 Answer

1

You could make a custom filter function to find elements with an attribute that starts with on , like so:

$.fn.filterOn = function() {
   this.each(function(ind,el) {
       var attrs = el.attributes;
       for (var i = 0; i < attrs.length; i++) {
           if (attrs[i].nodeName.indexOf('on') === 0) return true;       
       }
       return false;
   });
};

and use it like:

//elems will contain all input fields with an attribute starting with 'on'
elems = $(':input').filterOn(); 

And this will give you ALL elements in the page that has an attribute starting with on (beware of performance when using * selector):

$("*").filterOn().each(function() {
   console.log('Element '+this.tagName + ' has an on... attribute');
});
answered 2012-10-21T16:25:34.887

Your Answer