Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select elements with event attributes using Jquery?

Tags:

jquery

events

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

like image 905
user1408470 Avatar asked Oct 21 '12 15:10

user1408470


2 Answers

I believe that the short answer to your question is no.

Different HTML tags support different events, so they should be hardcoded somewhere in the jQuery code. And reading through the jQuery code, I cannot find any reference to onkeypress event, for example.

So, I think you can just rely on Has Attribute Selector [attribute]:

$('[onclick], [onkeypress], [etc]');
like image 163
Luca Fagioli Avatar answered Oct 23 '22 14:10

Luca Fagioli


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');
});
like image 33
Nelson Avatar answered Oct 23 '22 13:10

Nelson