What's the difference between
document.getElementById("id").click();
and
document.getElementById("id").onclick();
?
What's the difference between
document.getElementById("id").click();
and
document.getElementById("id").onclick();
?
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">