5

What's the difference between

document.getElementById("id").click();

and

document.getElementById("id").onclick();

?

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
user8476829
  • 81
  • 1
  • 1
  • 2

1 Answers1

11

click is a function on HTML elements you can call to trigger their click handlers: element.click();

onclick is a property that reflects the onclick attribute and allows you to attach a "DOM0" handler to the element for when clicks occur: element.onclick = function() { /*...*/}; (The modern equivalent is addEventListener("click", ...) [or attachEvent on obsolete versions of IE].) If you called onclick (element.onclick()), you'd call the function attached to it — but not handlers attached with modern methods.

E.g., click triggers a fake click; the other lets you set up a handler for clicks. (If you call onclick, it'll only call the handler attached via that old DOM0 mechanism.)

Example:

var btn = document.querySelector("input[type=button]");
// Add a modern handler to it
btn.addEventListener("click", function() {
  console.log("Modern handler called");
});
// Add an obsolete DOM0 handler to it
btn.onclick = function() {
  console.log("DOM0 handler called");
};
// Call `click`
console.log("Calling click():");
btn.click();
// Call `onclick` (which would be VERY unusual)
console.log("Calling onclick():");
btn.onclick();
<input type="button" value="Click Me">
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    `onclick` is a property so it should be accessed as `document.getElementById("id").onclick`, right? Won't `document.getElementById("id").onclick()` call the returned function? The behavior *might* be different though. – Ajay Brahmakshatriya Aug 17 '17 at 08:35
  • @AjayBrahmakshatriya: Yes, it would. I'll clarify. – T.J. Crowder Aug 17 '17 at 08:37
  • Also, won't `this` be different in both the cases? In `click()` it will be the object on which the handler is attached. In `onclick()` it would be a normal function call and `this` would be inherited from the calling context. (I am not sure about this). – Ajay Brahmakshatriya Aug 17 '17 at 09:23
  • 1
    @AjayBrahmakshatriya: *"it would be a normal function call and this would be inherited from the calling context"* That's not how `this` works. More: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work (And no, `this` would be the same in both cases, provided the functio[s] being called aren't bound or arrow functions.) – T.J. Crowder Aug 17 '17 at 09:27
  • Thanks! I was unsure about the case. – Ajay Brahmakshatriya Aug 17 '17 at 09:28