Moby04 Moby04 - 1 month ago 7
Javascript Question

Recursively remove empty nodes from html

I'd like to remove empty elements from some html string. I know I could run something like:

$('p').each(function(index, item) {
if($.trim($(item).text()) === "") {
$(item).remove();
}
});


The problem is that I want to remove all empty nodes - not only p. Also I want the script to consider p node in
<p><span></span></p>
as empty because it contains only empty elements. Do you have some simple implementation of something like that?

[EDIT]
I forgot to add: I can use jQuery but the html I want to traverse and edit is in a string - not the actual document. So how can I do this operation? I tried using
var html = $.parseHTML('<p><span></span></p>')
but after each loop I still get the same string...

Answer

Recently I was looking for a solution to the same problem. A recursive function was the answer.

function removeEmptyTagsRecursively($el) {
    if ($el.children().length) {

        $el.children().each(function(i, val) {
            removeEmptyTagsRecursively($(val));
        });

        $el.children(':empty').remove();
    }
}

Fiddle here: https://jsfiddle.net/635utakr/9/

Comments