简体   繁体   中英

How can I remove content like   from an element?

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?

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.net/p7v89/

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

That will find all text nodes and remove them.

You could alternatively try the .detach() method.

var $data = $('.container > div').detach();
$('.container').empty().html($data);

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, ' ');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM