1

So I have a DOM element that looks like this:

<span>text</span>
<b>some more text</b>
even more text here
<div>maybe some text here</div>

My question is how do I swap text for candy so it looks like this:

<span>text</span>
<b>some more text</b>
even more *candy* here
<div>maybe some text here</div>

I've tried a .replace with regex already but it swaps all the text occurrences.

Also I do not know where the text without tags will be. It could be in the middle at the beginning or at the end, (basically anywhere) I can't remove the child nodes either, because I don't know their positions and also if there is a <script> child it would probably rerun when I add it again at the end of all the text manipulation.

Can anyone point me in the right direction?

István
  • 5,057
  • 10
  • 38
  • 67
Andriy Lysak
  • 384
  • 5
  • 15

2 Answers2

3

You can check the nodeType property of the nodes:

$('#parent').contents().each(function() {
   if (this.nodeType === 3) {
      this.nodeValue = this.nodeValue.replace('text', 'candy');
   }
});

If you want to replace the text with HTML, you can use the replaceWith method:

$('#parent').contents().filter(function() {
   return this.nodeType === 3 && this.nodeValue.indexOf('text') > -1;
}).replaceWith(function() {
    return this.nodeValue.replace(/(text)/g, '<strong>candy</strong>');
});
Ram
  • 143,282
  • 16
  • 168
  • 197
  • this works great!!! What if i wanted to also swap it for `candy` and have it rendered as well? it seems `this` doesn't have a `.innerHTML` that i could use. – Andriy Lysak Jul 25 '14 at 22:26
  • @Andriy Yes, textNodes do not have `innerHTML` property. You can replace the textNode with the modified value. – Ram Jul 25 '14 at 22:37
1

Looks like I got beaten to the button, so here is an alternative way. I'm assuming all of those elements are enclosed in somesort of parent element, such as 'enclosingDiv'. If that is so, a simple answer would be:

    var e = document.getELmentById('enclosingDiv');

    var divAsString = String(e);
    var newDivAsString = divAsString.replace('text', 'candy');
    e.innerHTML = newDivAsString;
Hektor
  • 1,845
  • 15
  • 19