简体   繁体   中英

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?

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM