Remove spaces in image table

I have html like this.

<td id="foo">
    <img src="foo.png" /> <img src="foo.png" /> <img src="foo.png" />&nbsp; 
</td>

The HTML above contains spaces, and also &nbsp;,
I want to remove this using jQuery.
How to do it?

already tried with this script, but didn't work.

$('#foo').text().replace(/ /g,'');
+3
source share
4 answers

I think you need to use the content () and then filter out all text nodes that are simple space

var nodes = $("#foo").contents().filter(function() {
    return this.nodeType == 3 && /^(\s|&nbsp;)*$/.test(this.nodeValue);
}).remove();

//console.log($("#foo").html());
Perhaps something like this? if you only have images, you can just delete && this.data == " "part

I edited it to find spaces and now, the jsfiddle test: http://jsfiddle.net/Rurn2/

+1
source

: $('#foo').html($('#foo').html().replace(/ /g,''));? , . , .

0

:

var html = '>' + $('#foo').html() + '<';
html = html.replace(/&nbsp;/g, '').replace(/>\s+</gm, '><');
$('#foo').html(html.substring(1, html.length-1));
0

- nodeValue , , , . innerHTML , , (, , ). , . , :

$("#foo").contents().filter(function() {
    if (this.nodeType == 3) {
        return(this.nodeValue.replace(/\s|&nbsp;/g, "") == "");
    }
    return(false);
}).remove();​

, : http://jsfiddle.net/jfriend00/RNTbT/

FYI, this version even processes text nodes, which are a combination of and spaces &nbsp;. It works by removing all spaces and &nbsp;then looking through if something remains. If not, then this is text with a space, node, so it should be deleted.

0
source

All Articles