skip to Main Content

I have the following anchor tag.

<a href="www.google.com">Google</a>

When I click on the above link the URL will get mydomain.com/www.google.com
I have to say When I set href like the following

<a href="https://google.com">Google</a>

It works and goes to google.com

How can I have an anchor tag like this : <a href="www.google.com">Google</a>

2

Answers


  1. To ensure that the anchor tag <a href="www.google.com">Google</a> behaves as expected and navigates to the correct URL, you need to provide the complete URL including the protocol (e.g., "https://&quot😉 in the href attribute.

    If you omit the protocol, the browser will interpret the URL as a relative path instead of an absolute URL. In your case, www.google.com without a protocol will be treated as a relative path and appended to the current domain, resulting in mydomain.com/www.google.com

    To achieve the desired behavior, you can modify the href attribute as follows:

    <a href="https://www.google.com">Google</a>
    
    
    Login or Signup to reply.
  2. You need to add https:// in the beginning of an href attribute for anchor tags. That’s how it works and that’s what you should follow. But if you really want an alternative solution then you can try the cool trick that I have written with JavaScript.

    var all_a = document.querySelectorAll('a');
    
    for(i=0; i < all_a.length; i++){
        all_a[i].addEventListener('click', function(){
          this.setAttribute('href', 'http://' + this.getAttribute('href'));
        })
    }
    <a href="www.google.com">Google</a>
    <a href="www.facebook.com">Facebook</a>
    <a href="www.stackoverflow.com">Stackoverflow</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search