Search code examples
javascripthtmlhttpanchorhref

Make anchortext part of href?


I have a link that looks like this:

<a class="link" href="https://www.google.com/?q=">Hello world</a>

Is it possible to render this into Hello World?

The link should point to https://www.google.com/?q=Hello world without specifying this in the href.

I am thinking javascript is probably the best way of doing this?

Any help would be good!


Solution

  • Can you try this,

    <a class="link" href="https://www.google.com/?q=" onclick='window.location.href = this.href+encodeURI(this.textContent); return false; '>Hello world</a>
    

    Added onclick event handler and get the href and textContent of the tag and combine them together. Then it will give the expected result.

    Updated: If you have lot of links in your page, then you can create javascript function and call it wherever necessary.

    Javascript:

     function Search(d){
         window.location.href = d.href+encodeURI(d.textContent); 
        return false; 
     }
    

    HTML:

     <a class="link" href="https://www.google.com/?q=" onclick='Search(this);'>Hello world</a>
    

    Even if you feel to integrate jquery, the process may get simpler.