最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I remove content like   from an element? - Stack Overflow

programmeradmin2浏览0评论

I have a div where the content looks like this:

<div class="container">
    &nbsp;
    <div class="eventSpot bg-blue"></div>
    <div class="eventSpot bg-blue"></div>
    <div class="eventSpot bg-red"></div>
</div>

The &nbsp; is causing some styling problems so I need to remove it.

How can I remove just that part of the content with jQuery/javascript?

I have a div where the content looks like this:

<div class="container">
    &nbsp;
    <div class="eventSpot bg-blue"></div>
    <div class="eventSpot bg-blue"></div>
    <div class="eventSpot bg-red"></div>
</div>

The &nbsp; is causing some styling problems so I need to remove it.

How can I remove just that part of the content with jQuery/javascript?

Share Improve this question edited May 8, 2014 at 13:58 user247702 24.3k18 gold badges115 silver badges160 bronze badges asked May 8, 2014 at 13:54 TomTom 13k50 gold badges153 silver badges247 bronze badges 5
  • Why can't you remove it in html code itself ? – Ani Commented May 8, 2014 at 13:56
  • Do you only want to remove the &nbsp; or any non-tag-contents (if you know what I mean ;)) – giorgio Commented May 8, 2014 at 13:57
  • It's not put there by me, it's inserted in by a third party plugin. So I need to remove it after the page is rendered – Tom Commented May 8, 2014 at 13:57
  • 2 This should help: stackoverflow./questions/15345631/remove-nbsp-from-html – Ani Commented May 8, 2014 at 13:58
  • How do you define “just that part”? Do you mean any NO-BREAK SPACE in the content, or just a single one in a particular context (exactly which?)? – Jukka K. Korpela Commented May 8, 2014 at 14:52
Add a ment  | 

4 Answers 4

Reset to default 5

Using jQuery:

var div = $('div.container');
div.html(div.html().replace(/^\s*&nbsp;/m, ''));

I prefer working with nodes instead of html as a string if possible, so I would suggest something like this:

http://jsfiddle/p7v89/

$('.container').contents().filter(function() {
    return this.nodeType == 3
}).remove();

That will find all text nodes and remove them.

you will get the text without HTML tag and &nbsp etc

This is a solution for HTML tag and &nbsp etc and you can remove and add conditions

convertHtmlToText(passHtmlBlock)
{
   str = str.toString();
  return str.replace(/<[^>]*(>|$)|&nbsp;|&zwnj;|&raquo;|&laquo;|&gt;/g, ' ');
}

You could alternatively try the .detach() method.

var $data = $('.container > div').detach();
$('.container').empty().html($data);
发布评论

评论列表(0)

  1. 暂无评论