koushik
koushik

Reputation: 99

Find out div with class name and remove   before and after it

I have a formatted text field which contains..

"this is some text node 
<div class="myClass">contents....</div>
&nbsp;some more text node&nbsp;
<div class="myClass">contents....</div>
&nbsp;"

..like this.

Now i want to remove all the surrounding "&nbsp" to those divs which has class="myClass" only i.e the "&nbsp" before and after those divs.

I have gone through this link but it is not solving my problem

jquery how to find if div with specific id exists

Thanks in advance.

Upvotes: 0

Views: 2196

Answers (3)

koushik
koushik

Reputation: 99

var text = '"this is some text node&nbsp;&nbsp; <div  class="myClass"> contents....</div> &nbsp;&nbsp;"';    
var $ct;
$ct = $('<pre />', {
    html: text
});

$ct.find('.myClass').each(function () {
    if (this.nextSibling && this.nextSibling.nodeType == 3) {        
        var r = this.nextSibling.data;
        this.nextSibling.data = this.nextSibling.data.replace(String.fromCharCode(160), '');
        var s = this.nextSibling.data;
        this.nextSibling.data = this.nextSibling.data.replace(/^&nbsp;/, '');
    }
    if (this.previousSibling && this.previousSibling.nodeType == 3) {
        this.previousSibling.data = this.previousSibling.data.replace(String.fromCharCode(160), '');
        this.previousSibling.data = this.previousSibling.data.replace(/&nbsp;/, '');
    }
})

var html = $ct.html();
alert(html);

Thanks to all. I just modified Mr. Arun P johny's code a little. And thats worked for me perfectly. In his code it was deleting blank space also, but i wanted to delete &nbsp only.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

I might go for something like

var text = '"this is some text node&nbsp;<div  class="myClass"> contents....</div>&nbsp;some more text node&nbsp;<div  class="myClass"> contents.... </div>&nbsp;"';

var $ct = $('<div />', {
    html: text
});

$ct.find('.myClass').each(function () {
    if (this.nextSibling && this.nextSibling.nodeType == 3) {
        this.nextSibling.data = this.nextSibling.data.replace(/^\s+/, '');
    }
    if (this.previousSibling && this.previousSibling.nodeType == 3) {
        this.previousSibling.data = this.previousSibling.data.replace(/\s+$/, '');
    }
})

var html = $ct.html();

Demo: Fiddle

Upvotes: 3

Jey
Jey

Reputation: 60

you can replace '' instead of '& nbsp;',

$('.myClass').html($('.myClass').html().replace('&nbsp;',''));

or try like this,

$('.myClass').html(function(i,h){
return h.replace(/&nbsp;/g,'');});

Upvotes: 0

Related Questions