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 ?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With