What is the difference between addEventListener and onclick?

Ask a question+

There are 2 examples that adding a click event listener:

var h = document.getElementById(“a”);
.onclick = dothing1;
.addEventListener(“click”, dothing2);

The code above resides together in a separate .js file, and they both work perfectly.
But I wonder what the difference between them is?

BabkenM 870
add comment

1 Answer


onclick() and addEventListener() methods functionality are same. But the difference between that is below.
We can use onclick method only on elements like button element(<button>), anchor element(<a>). But we can not use it directly on div(<div></div>) element, span element etc.
We can use addEventListener in every elements by register that element in addEventListener() method.

Abikananda 50
add comment

Your Answer