JQuery to remove s but without using .html () which recreates everything

I have many elements inside CKEditor with events associated with them and data associated with them using the .data () method. I would like to remove any & ampnbsp; s from this HTML block. I could just do

$('body').html($('body').html().replace(/&nbsp\;/, ''));

      

But since this dumps the HTML, it effectively recreates all the elements, which means I have to relink all events and data. I am currently doing the following:

if ($body.html().indexOf(' ') > -1) {
    $body.find(':*:not(:has(*))').each(function(){
            // These nodes don't have any children so contain text or nothing
            $(this).html($(this).html().replace(/&nbsp\;/,''));
    });
}

      

This will replace & ampnbsp; s in HTML as follows:

     <p>Foo&nbsp;Bar</p>

      

But not in HTML:

     <div>Foo&nbsp;<span>Bar</span></div>

      

Can anyone think of a better way to do this?

Thank,

Joe

+3


source to share


2 answers


Just select all the text nodes inside the target element and then go through them making the replacement.

$("*").contents().filter(function(){
    return this.nodeType === 3;
}).each(function(){
    // do your replace here using this.nodeValue
});

      



I highly recommend filtering to a smaller subset of items if possible '*'

and 'body *'

is likely to be slow.

+2


source


Your first code seems $('body').html($('body').html().replace(/&nbsp\;/, ''));

to be correct. you just need to add g

at the end to replace all occurrences and make sure you call this function when you load the document like here.



$('document').ready(function () { $('body').html($('body').html().replace(/&nbsp\;/g, '')); });

0


source







All Articles