Add href text for link if clicked
I have a page with multiple links. Several links point to the same exact URL. I want to add text (linked href text) to a link that is clicked (or hoisted?) When one of these duplicate links is clicked.
So far, I can only add the first link text, but not the one I click.
I've tried a few things, but I'm still learning JavaScript (I envy you all) and I'm afraid I keep messing it up than I try. I know I will probably have to use the hang or modify in some way 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 "dog" link, I want to open a new browser tab / window with the url " http://www.1.com "
When I click on the "cat" link, I want to open a new browser tab / window with the url " http://www.2.com "
When I click on the link "bird" I want to open a new browser tab / window with the url "bird"
When I click the frog link, I want to open a new browser tab / window with the frog url
So, any link that has http://www.3.com "because the href will ignore" http://www.3.com "and instead open a new browser tab / window with the text that was just clicked.
Also, I can't seem to add IDs, class, script, etc. to links / HTML, so I need to figure out how to do this, like JS referencing the href, not inside HTML.
source to share
A colleague of mine found a solution. Thanks everyone for your help.
Option 1:
Replace some of my original JS:
"document.getElementsByTagName (" a ") [0] .innerHTML"
from:
"window.location"
or
Option 2: jsfiddle
Replace all 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;
});
FROM
var anchors = $('a[href$="http://www.3.com"]');
$.each(anchors, function (index, element) {
$(element).attr('href',$(element).text());
});
source to share
Not sure if this is exactly what you are asking for, but THIS DEMO is an example where I take the href and add it to the text.
Html
<a href='#' onclick='change(this)'>link one</a>
<a href='#' onclick='change(this)'>link two</a>
<a href='#' onclick='change(this)'>link three</a>
<a href='#' onclick='change(this)'>link four</a>
CSS
a {
float: left;
clear: both;
}
Javascript
function change(variable) {
variable.innerHTML = variable.innerHTML + variable.href;
}
source to share