[英]Change text between tags with javascript
I'd like to change some text that is between those tags : 我想更改这些标签之间的一些文本:
<div id=thing>
<a href=link></a>texttochangehere<a href=link2></a>
</div>
But without changing the links. 但无需更改链接。 I tried replacing only the part I want with innerHTML and substring, but it seems to unlink the tags that another script uses. 我尝试用innerHTML和子字符串仅替换我想要的部分,但似乎无法链接另一个脚本使用的标签。
There are at least two ways to achieve your goal: 至少有两种方法可以实现您的目标:
innerHTML
) 字符串替换和HTML解析(使用innerHTML
) textContent
) DOM操作设置文本节点(使用textContent
) var div = document.getElementById('thing');
// replace text in HTML string:
div.innerHTML = div.innerHTML.replace('texttochangehere','changedtext');
// manipulating text node:
for(var node of div.childNodes){
if(node.nodeType == 3 && node.textContent == 'texttochangehere')
node.textContent = 'changedtext';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.