Reputation: 11
I want to write a Javascript function to change the text google in an HTML tag: example:
<a href='http://google.com'>google</a>
How can I change the text in an HTML tag "google" but not change the content "http://google.com" that is in an href link?
Upvotes: 1
Views: 99
Reputation: 36703
If you are using Vanilla JS (plain javascript) then you need to find the a
tag by looping among all a
and finding the one with href
http://google.com
and then replace it's innerHTML
.
var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === 'http://google.com') {
el.innerHTML = "New Content";
}
}
Explaination:
A. document.getElementsByTagName
will return you the list of all elements matching the passed tag.
B. el.href
will get you the href
of the a
.
C. el.innerHTML = "New Content"
will set the new content.
Upvotes: 5