6. Event Element Binding
Rule #5: HTML Event Element Binding in JavaScript
In HTML event handlers, this binds to the HTML elements that receive the event.
<button onclick="console.log(this)">Click Me!</button>
The is the output log in the console when you click on the button:
"<button onclick='console.log(this)'>Click Me!</button>"
You can change the button style using the this keyword, like this:
<button onclick="this.style.color='teal'">Click Me!</button>
But be mindful when you call a function on the button click and use this inside that function.
<button onclick="changeColor()">Click Me!</button>
and the JavaScript:
function changeColor(){this.style.color='teal';}
The above code won't work as expected. As we have seen in the Rule 4, here this will be bound to the global object (in the 'non-strict' mode) where there is no style object to set the color.