11

My naive approach is the following:

function isClickable(id){     
     elem = document.getElementById(id);
     if (elem.nodeName.toLowerCase() == 'a' || typeof(elem.click) != 'undefined'){
        return true;     
     }else{
        return false;     
     }
}    

Is there anything better I can do?

Guy
  • 14,178
  • 27
  • 67
  • 88
  • 3
    i mean, technically everything is clickable... – Jason Apr 12 '11 at 07:57
  • You're right. Would it help if I rephrase to: "if I click on it, will something happen?" – Guy Apr 12 '11 at 08:00
  • what are you trying to accomplish by determining this? – Jason Apr 12 '11 at 08:01
  • Actually Firefox needs a nasty script to make it possible to click some html elements programatically – mplungjan Apr 12 '11 at 08:01
  • My goal is testing - after I do some action, does an element become clickable (stops being clickable) – Guy Apr 12 '11 at 08:04
  • Do radiobuttons, checkboxes etc fall under the "clickable" term? I mean, you must better define what you mean by "clickable" or "something happen". So far, you have shown you want to detect hyperlinks and elements that have a `click` event defined. But there are more of them - mousedown, dblclick event, imagemaps etc. – František Žiačik Apr 12 '11 at 08:05
  • Also - when using bubbling you can make anything clickable without leaving much of a trace - see jQuery.live() – naugtur Apr 12 '11 at 08:34
  • Depends - are you in control of adding those events? When replying please use `@namehere` to notify the people e.g. `@Shadow` otherwise we won't see your replies here. – Shadow The GPT Wizard Apr 12 '11 at 11:00

1 Answers1

2

For most elements...

if(e.getAttribute('onclick')!=null){

 // clickable

}

For anchors...

if(e.getAttribute('href')!=null){

 // clickable

}

Then you have form buttons which require a little more code, and finally you have click-event bubbling to deal with so a perfect solution covering ALL elements would be a nightmare!

However, if you just want something SIMPLE for containers and anchors only, then we can combine the logic above with a...

if((e.getAttribute('onclick')!=null)||(e.getAttribute('href')!=null)){

 // clickable

}

For the reverse...

if((e.getAttribute('onclick')===null)&&(e.getAttribute('href')===null)){

 // not clickable

}
  • 1
    This works quite well but on top of that I added this check too if(element.getAttribute('role') === "button") – miso01 Jan 18 '21 at 19:27