How to prevent replaceWith from creating multiple text nodes?

I have this html code:

<p><span>h</span><span>o</span><span>l</span><span>a</span></p>

And I use jQuery on it to replace all the gaps:

$('p span').each(function(){
   $(this).replaceWith($(this).text());     
});

When I look through my DOM, I see a script created 4 text nodes for each letter. How can I prevent this? I want only 1 text node!

Note: this example is very simplified. I actually do this:

<p>This is an <b>example</b>: <span>h</span><span>o</span><span>l</span><span>a</span>!</p>

It should look like this:

<p>{text}This is an {/text}<b>{text}example{/text}</b>{text}: hola!{/text}</p>

{text} is the DOM text of node :-)

+3
source share
2 answers

One thing you can do is end up calling your own method normalize():

$('p').find('span').each(function(){
   $(this).replaceWith($(this).text());     
}).end()[0].normalize();

EDIT: parent() (docs), <span>, DOM, .

<p>, find() (docs) <span>. , end() (docs), <p> .normalize().

<p>, .

$('p').find('span').each(function(){
   $(this).replaceWith($(this).text());     
}).end().each(function() {
    this.normalize();
});

replaceWith() (docs), .

$('p').find('span').replaceWith(function(i,el){ 
    return $.text([this]);
}).end().each(function() {
    this.normalize();
});
+2

, ?

$('p').text(function (i, txt) {
    return txt;
});

: http://jsfiddle.net/2qNGY/

+1

Source: https://habr.com/ru/post/1786922/