Difference between onclick attribute and onclick property

You may have known quite a few methods to bind a handler to the click event on an element, two of which are using the onclick attribute and the onclick property, like:

<li id="li" onclick="alert('hello');">content</li>

 

<li id="li">content</li>
<script>
var li=document.getElementById("li");
li.onclick =function(e){
    alert("hello");
}
</script>

What is the difference between the onclick attribute and the onclick property? Well, in modern browsers, the onclick attribute is a string which represents a piece of valid javascript code, while the onclick property is a function(reference). The onclick attribute will be used to generate the onclick property which is an anonymous function containing the js code. If you use both the onclick attribute and the onclick property, the code of the onclick attribute will be overwritten and you have got only one event handler.

Note that the following usage of the onclick attribute is not correct.

<li id="li" onclick="function(e){alert('hello');}">content</li>

and will produce the error “Uncaught SyntaxError: function statement requires a name”. This is because an anonymous function cannot be defined without using it. Giving a name to the function does not work as you expect:

<li id="li" onclick="function a(e){alert('hello');}">content</li>

This time, no error is produced but you cannot see the alert window because the code just contains the declaration of the function, not the execution of the function. The correct usage is:

<li id="li" onclick="function a(e){alert('hello');a();} ">content</li>

You can see the code in the onclick attribute becomes complex and not easy to read. If you need complex handler logic, you’d better use the onclick property. In fact, I do not suggest to use the onclick attribute except for very simple cases as the hidden logic under the hood of the onclick attribute may surprise you.

 

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply