[英]How can I replace the text in an HTML tag but not in an href link?
I want to write a Javascript function to change the text google in an HTML tag: example: 我想编写一个Javascript函数来更改HTML标记中的文本google:示例:
<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? 如何更改HTML标记“ google”中的文本,而不更改href链接中的内容“ http://google.com ”?
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
. 如果您使用的是Vanilla JS(普通javascript),则需要通过在所有
a
之间循环并使用href
http://google.com
找到a
标签来找到a
标签,然后将其替换为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. 答:
document.getElementsByTagName
将返回与已传递标签匹配的所有元素的列表。
B. el.href
will get you the href
of the a
. B.
el.href
将让你的href
中的a
。
C. el.innerHTML = "New Content"
will set the new content. C.
el.innerHTML = "New Content"
将设置新内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.