Why is it bad practice to use links with the javascript: “protocol”?

The execution context is different, to see this, try these links instead:

<a href="https://stackoverflow.com/questions/2479557/javascript:alert(this.tagName)">Press me!</a> <!-- result: undefined -->
<a href="#" onclick="alert(this.tagName)">Press me!</a> <!-- result: A -->

javascript: is executed in the global context, not as a method of the element, which is usually want you want. In most cases you’re doing something with or in relation to the element you acted on, better to execute it in that context.

Also, it’s just much cleaner, though I wouldn’t use in-line script at all. Check out any framework for handling these things in a much cleaner way. Example in jQuery:

$('a').click(function() { alert(this.tagName); });

Leave a Comment