简体   繁体   中英

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.

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM