找出具有类名的div并在其之前和之后删除

时间:2014-08-08 11:43:44

标签: javascript jquery html

我有一个格式化的文本字段,其中包含..

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

现在我要移除所有周围的&#34; &nbsp&#34;对那些只有class="myClass"的那些div,即&#34; &nbsp&#34;在那些div之前和之后。

我已经通过了这个链接,但它没有解决我的问题

jquery how to find if div with specific id exists

提前致谢。

3 个答案:

答案 0 :(得分:3)

我可能会选择像

这样的东西
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();

演示:Fiddle

答案 1 :(得分:0)

你可以替换&#39;&#39;而不是&#39;&amp; NBSP;&#39;,

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

或尝试这样,

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

答案 2 :(得分:0)

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

感谢所有人。我刚刚修改了Arun P johny先生的代码。这对我来说非常有用。在他的代码中它也删除了空格,但我想删除&amp; nbsp only。