Reputation: 43
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.
Upvotes: 3
Views: 356
Reputation: 43
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());
});
Upvotes: 0
Reputation: 172378
Try like this:
<a href="" onClick="javascript:this.innerHTML = 'ChangedClickMe'">ClickMe</a>
Upvotes: 2
Reputation: 10021
Not sure if this is exactly what you're asking for but THIS DEMO is an example where I take the href and append 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;
}
Upvotes: 0