Moby04 Moby04 - 1 year ago 129
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()) === "") {

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

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 Source

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) {


Fiddle here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download