Reputation: 109
I would like to replace g
characters on the following innerHTML div:
<div id="myDiv">aaa>aga</div>
I used
var myDiv = document.getElementById('myDiv');
myDiv.innerHTML = myDiv.innerHTML.replace('g','a');
Unfortunately, this replace also the >
character by &at;
.
How can I do to avoid this behavior ?
Upvotes: 3
Views: 1638
Reputation: 36448
If you want to be extra safe (when dealing with elements that contain other elements, or text that you don't want interpreted as HTML), you'll want to loop through the element's children to find Text nodes within.
A simple replacement inside the Text nodes will get you what you want:
function replaceIn(el, pattern, replacement) {
if (el.nodeType == 3) { // TEXT_NODE
el.nodeValue = el.nodeValue.replace(pattern, replacement);
}
else {
var n = el.childNodes.length;
for (var i = 0; i < n; ++i)
replaceIn(el.childNodes[i], pattern, replacement);
}
}
replaceIn(document.getElementById('foo'), /two/g, 'dos');
<div id="foo">
<p>one</p>
<p><em>two</em>
</p>
one two <em>three</em> four two two three four
</div>
Upvotes: 3
Reputation: 77482
Try use .innerText
instead of .innerHTML
, like so
var myDiv = document.getElementById('myDiv');
var text = myDiv.innerText || myDiv.textContent || '';
myDiv.innerHTML = text.replace(/g/g, 'a');
// or without variable
// myDiv.innerHTML = (myDiv.innerText || myDiv.textContent || '').replace(/g/g, 'a');
<div id="myDiv">aaa>aga</div>
Upvotes: 5