8

I found the way to check if event exists on element. But it's not work on the events which is not delegated by jQuery:

When I try,

$("a").data("events");

for this.

<a href="#" onClick="alert('Hello, World!')" />

It returned undefined.

Is there any way to check if onClick exists on elements with jQuery?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Ei Maung
  • 7,013
  • 5
  • 23
  • 23

5 Answers5

20

You can do:

if ($('a').attr("onClick") != undefined) {}
Tim Ebenezer
  • 2,714
  • 17
  • 23
8

Just do:

if( myelement.onclick != null )
{
   //onclick exists
}
else
{
   //onclick doesn't exist
}

No need for jQuery.

Gabriel Hautclocq
  • 3,230
  • 2
  • 26
  • 31
  • 2
    I'm trying to test if an event listener has been setup as part of a JS Unit test... how how can i test if it has been setup or not?? This isn't working, always returns true... console.log(document.body.click.length); document.body.addEventListener('click', function () { alert('hi')},false) console.log(document.body.click.length); – Will Hancock Oct 05 '12 at 10:58
3
if( $('#elementName').click == undefined)  
   { //event handler doesn't exist }
else 
   { //handler exists }
pencilslate
  • 12,958
  • 18
  • 58
  • 73
0

For sure there are some valid answers here, this was a good one that got me going.

if ($('a').attr("onClick") != undefined) {}

But I found the best answer for you, as it was for since we are both dealing with hyperlinks, would looking for the href attribute.

if ($('a').attr("href") != undefined) {}

I particularly liked this approach.

Chef Pharaoh
  • 2,387
  • 3
  • 27
  • 38
0

I think the following things should also work

if ($(yourElement).attr("onClick").length != 0) {}

if ($(yourElement).attr("onClick").size() != 0) {}

Thanks

Mahesh Velaga
  • 21,633
  • 5
  • 37
  • 59