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.

2

1 Answer 1

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';
}
Sign up to request clarification or add additional context in comments.

1 Comment

In lieu of the magic number 3, we can also use the equivalent constant Node.TEXT_NODE, which might improve readability. (See MDN, DOM Standard)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.