Andriy Lysak
Andriy Lysak

Reputation: 384

Swapping text in a DOM element with children JavaScript/jQuery

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?

Upvotes: 1

Views: 97

Answers (2)

Ram
Ram

Reputation: 144739

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

Upvotes: 3

Hektor
Hektor

Reputation: 1945

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;

Upvotes: 1

Related Questions