Sometimes, we want to add a relative URL to a different port number in a hyperlink with HTML.
In this article, we’ll look at how to add a relative URL to a different port number in a hyperlink with HTML.
How to add a relative URL to a different port number in a hyperlink with HTML?
To add a relative URL to a different port number in a hyperlink with HTML, we set the onclick
attribute to JavaScript code that redirects to the destination.
For instance, we write
<a href="#" onclick="window.open(`${window.location.hostname}:8080/foo`)">
Link to some other port on the same host
</a>
to set the onclick
attribute to window.open(`${window.location.hostname}:8080/foo`)
to open the URL in a new tab.
We get the existing URL’s host name with window.location.hostname
and then put the port after it.
Conclusion
To add a relative URL to a different port number in a hyperlink with HTML, we set the onclick
attribute to JavaScript code that redirects to the destination.