jaredwilli
jaredwilli

Reputation: 12308

How would you detect if an element is empty but has spaces and carriage returns to trim them with JavaScript / jQuery?

I'm trying to use $.trim() to trim whitespace in empty elements so I can check the length of an element to see if it has text content in it and if it does not then remove it from the DOM.

Some elements are returning a length of greater than 0 because they have spaces and/or carriage returns in them which is all that is contained in them.

I basically need to find and remove any empty tags when they have nothing in them.

I don't suppose anyone knows of a simple quick way to just check for and remove any empty tags in the main content of a page, whether they contain any whitespace chars or not by any chance? I'm sure there must be a way.

Upvotes: 0

Views: 367

Answers (4)

jjmontes
jjmontes

Reputation: 26895

Try this:

$('body *').each(function(idx, element) {
    if ($(element).children().size() == 0) {
        if ($(element).text().trim() == "") {
            $(element).remove();
        }
    }
});

You may need to further fine-tune the selector a bit, but it should do it.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

$('body *').each(function() {
    if (!$.trim($(this).text())) {
        $(this).remove();
    };
});

Don't expect it to run very efficiently, though.

Upvotes: 1

pimvdb
pimvdb

Reputation: 154838

You'd want to check for elements in the body only, since otherwise script tags and other non-content elements also get removed: http://jsfiddle.net/6zdNf/1/.

// filter empty elements after trimming
$("body *").filter(function() {
    return $.trim($(this).html()) === "";
}).remove(); // remove them

Upvotes: 5

daan
daan

Reputation: 254

Simply use jQuery filter with a function:

var rege = /\S/gi;
$('div').filter(function(){
  return rege.test($(this).text())
});

After using this code, you'll only have divs left with text in it! Use with caution on images, since they do not have any text!

The regular expression /\S/gi test for a non-space character. Empty tags won't match and will return false.

Upvotes: 1

Related Questions