How does inline Javascript (in HTML) work?

You’ve got it nearly correct, but you haven’t accounted for the this value supplied to the inline code.

<a href="#" onclick="alert(this)">Click Me</a>

is actually closer to:

<a href="#" id="click_me">Click Me</a>
<script type="text/javascript">
document.getElementById('click_me').addEventListener("click", function(event) {
    (function(event) {
        alert(this);
    }).call(document.getElementById('click_me'), event);
});
</script>

Inline event handlers set this equal to the target of the event.
You can also use anonymous function in inline script

<a href="#" onclick="(function(){alert(this);})()">Click Me</a>

Leave a Comment