Reputation: 57
I have not done anything. But like to ask if there is any way I can achieve this feature.
I have a loop in my WordPress site whose output is something like this:
<div class="dummy">
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
</div>
Here you can notice all the URL are same.
So what I want to know here is, if there is a way I can redirect the 3rd or 4th anchor tag to a different URL like http://facebook.com using javascript?
If there is any such way possible, please let me know. I am curious about that.
Thank you in advance.
Upvotes: 0
Views: 86
Reputation: 361
Give id
to each anchor tag.
<div class="dummy">
<a id="anchor_1" href="http://google.com">Text Here</a>
<a id="anchor_2" href="http://google.com">Text Here</a>
<a id="anchor_3" href="http://google.com">Text Here</a>
<a id="anchor_4" href="http://google.com">Text Here</a>
<a id="anchor_5" href="http://google.com">Text Here</a>
</div>
Then use following javascript code to pick desired element and change its href
property.
<script>
document.getElementById("anchor_5").href = "http://www.facebook.com";
</script>
EDIT
If your website contains only these anchor tags, then you can get all the anchor tags and then select the last one ( or any other desired ) using index.
Here is a sample code
var anchors = document.getElementsByTagName("a");
var lastAnchor = anchors[(anchors.length - 1)];
In other case if you want the list of anchor tags of this particular div. (Assuming that there is only one div
having this class name)
var ancestor = document.getElementsByClassName('dummy')[0];
var descendents = ancestor.getElementsByTagName('a');
descendents[4].href="http://facebook.com"
Hope this helps. Let me know if there is some issue.
Upvotes: 1
Reputation: 962
Just select the a
tag you want to change, using whatever method makes the most sense, and literally just element.href = "www.example.com"
var first = document.getElementById("first");
first.href = "http://stackoverflow.com"
<div class="dummy">
<a id="first" href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
<a href="http://google.com">Text Here</a>
</div>
Upvotes: 0