Why does 'this' context differ between anchor links and list items in JavaScript?

I’m having trouble understanding how the this keyword works in different HTML elements. Here’s my code example:

<tr><td><a href="javascript:console.log(this)">click me</a></td></tr>
<ul><li onclick="console.log(this)">test item</li></ul>

When I click the anchor tag, this points to the window object. But when I click the list item, this refers to the HTMLLiElement itself. Can someone explain why these two elements handle the this context differently? I expected both to behave the same way since they’re both HTML elements with JavaScript code attached to them.

Yeah, this tripped me up when I started too. Here’s the deal: javascript: URLs run in the global context, so they can’t access the element that triggered them. It’s basically like throwing code in a <script> tag at the top level. But onclick is an actual event handler, so the browser automatically binds the element as context when it fires. Had to debug this mess myself before I figured it out - now I just skip javascript: URLs completely since they’re terrible for accessibility anyway. Proper event listeners are way more predictable.

The difference is how JavaScript handles this in each context. With href="javascript:...", the code runs in global scope, so this points to the window object - just like code at the top level of a script. But onclick on the list item creates an event handler bound to that element, so this becomes the element itself when clicked. If you want consistent behavior, ditch the inline handlers and use addEventListener instead, or just switch the anchor to use onclick too.

totally get you! that javascript: in href throws you off, right? it runs in the global scope so this is window. but with onclick, it’s bound to the element itself, making this the li. once you know it, it clicks!