Search code examples
javascriptjqueryhtmlhyperlinkhref

Add href text to link if clicked


I have a page with several links. Some links point to the same exact URL. I want to add the text (the linkable href text) to the link that is clicked (or hovered?) when one of these duplicate links are clicked.

So far I can only seem to add the first link's text but not the one I click.

I have tried a few things but I am still learning JavaScript (I envy you all) and am afraid I keep messing it up the harder I try. I know I will likely have to use hover or somehow change getElementsByTagName("a")[0]... Any help would be greatly appreciated!

<p>
<a href="http://www.1.com" target="_blank">dog</a>
<a href="http://www.2.com" target="_blank">cat</a>
<a href="http://www.3.com" target="_blank">bird</a>
<a href="http://www.3.com" target="_blank">frog</a>
</p>

Javascript:

$var anchors = document.querySelectorAll('a[href$="http://www.3.com"]');
Array.prototype.forEach.call(anchors, function (element, index) {
    element.href = document.getElementsByTagName("a")[0].innerHTML;
});

Example When I click on the link "dog", I want to open a new browser tab/window with the URL of "http://www.1.com"

When I click on the link "cat", I want to open a new browser tab/window with the URL of "http://www.2.com"

When I click on the link "bird", I want to open a new browser tab/window with the URL of "bird"

When I click on the link "frog", I want to open a new browser tab/window with the URL of "frog"

So any link that has "http://www.3.com" as the href will ignore the "http://www.3.com" and instead open a new browser tab/window with the text that was just clicked.

Also, I am unable to add IDs, Class, script, etc. to the links/HTML so I have to figure out how to do all of this as JS referencing the href and not inside of the HTML.


Solution

  • A colleague of mine found the solution. Thank's everyone for your help.

    Option 1:

    Replace part of my original JS:

    "document.getElementsByTagName("a")[0].innerHTML"

    with:

    "window.location"

    Or

    Option 2: jsfiddle

    Replace all of my original JS:

    $var anchors = document.querySelectorAll('a[href$="http://www.3.com"]');
    Array.prototype.forEach.call(anchors, function (element, index) {
    element.href = document.getElementsByTagName("a")[0].innerHTML;
    });
    

    With:

    var anchors = $('a[href$="http://www.3.com"]');
    $.each(anchors, function (index, element) {
    $(element).attr('href',$(element).text());
    });