最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Change text between tags with javascript - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question asked Jun 25, 2013 at 15:56 keywckeywc 31 silver badge2 bronze badges 2
  • textContent vs. innerHTML. See also innerText. – Teemu Commented Jun 25, 2013 at 15:58
  • 1 stackoverflow./a/8118165/2256325 – Sergio Commented Jun 25, 2013 at 15:59
Add a ment  | 

1 Answer 1

Reset to default 6

There are at least two ways to achieve your goal:

  1. String replacement and HTML parsing (using innerHTML)
  2. DOM manipulation setting the text node (using 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';
}
发布评论

评论列表(0)

  1. 暂无评论