Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 605
Liu Kang Avatar asked Jul 24 '14 06:07

Liu Kang


2 Answers

assuming your href is always in format https://www.google.com/?q=, you could do:

var eles = document.getElementsByTagName('a');
for(var i = 0, len = eles.length; i < len; i++) {
    //get the inner html of anchor tag
    //var text = eles[i].innerHTML;
    //better use textContent
    var text = eles[i].textContent;
    //append anchor tag inner html to href
    eles[i].href += text;
}
like image 117
Sudhir Bastakoti Avatar answered Oct 09 '22 02:10

Sudhir Bastakoti


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.

like image 22
Krish R Avatar answered Oct 09 '22 01:10

Krish R