Reputation: 805
Many websites offer external links to other websites. Some of them use hyperlinks:
<a href="https://example.com">Click me</a>
Others use buttons:
<button onclick="window.location.assign('https://example.com');">Click me</button>
It turns out that buttons use the window object to load pages, while hyperlinks use <a>
elements.
According to the HTML5 validator published by the W3C, the button element should not be a child of the a element.
This fails:
<button>
<a href="https://stackoverflow.com">See New Questions</a>
</button>
But window.location.assign
is the same as the a element, as shown by this snippet:
$('button').click(function() {
window.location.assign('https://stackoverflow.com');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>See New Questions</button>
<a href="https://stackoverflow.com">See New Questions</a>
So why does the W3C prefer window.location.assign()
over <a>
elements for HTML buttons?
Upvotes: 0
Views: 361
Reputation: 2013
window.location.assign is not just used in HTML you can use it to dynamically change the web address. for example you may want to after login redirect user to another page but you need to finish the login process first so you do the process and after the login was successful you use this function to change to another address. and there can be many other use cases like this one.
another difference is when you use this method it won't work on browsers that have disabled the javascript.
and for the third reason there can be multiple ways to done the same thing and people can choose which method do they like and have their own opinions on how you should do some action.
Upvotes: 1