user1408470
user1408470

Reputation: 1515

How to select elements with event attributes using Jquery?

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

Upvotes: 9

Views: 256

Answers (4)

jwaliszko
jwaliszko

Reputation: 17064

If the value is not specific, you can try this approach.

The demo below prints "hey you people", based on $([attr1],[attr2],...,[attrN]) selector:

<div class="container">
    <div>no id</div>
    <div id="a">hey</div>
    <span name="b">you</span>
    <p id="c">guys</p>
</div>​

$('[id],[name]').each(function(){
    console.log($(this).text());
});​

Based on that construction, simple wrapper can be written:

$.fn.hasAttrib = function() {   
    var attributes = [];
    $.each(arguments, function(index, value){
        attributes.push('[' + value + ']');
    });
    return $(this).find(attributes.join());
};

Usage of such plugin in the statement below also prints "hey you people":

$('.container').hasAttrib('id','name').each(function(){
    console.log($(this).text());
});

Upvotes: 1

Luca Fagioli
Luca Fagioli

Reputation: 13349

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]');

Upvotes: 4

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');
});

Upvotes: 1

sdespont
sdespont

Reputation: 14025

You could parse all elements and check. Not really efficient, but it should works.

Check get all elements with onclick in them?

var allElements = document.getElementsByTagName('*');
for ( var i = 0; i<allElements.length; i++ ) {
    if ( allElements[i].className !== 'theClassNameYoureLookingFor' ) {
        continue;
    }
    if ( typeof allElements[i].onclick === 'function' ) {
        // do something with the element here
        console.log( allElements[i] );
    }
}

Upvotes: 0

Related Questions