Skip to content Skip to sidebar Skip to footer

Regex To Remove Empty Html Tags, That Contains Only Empty Children

I need to parse an HTML string and remove all the elements which contain only empty children. Example:

Solution 1:

This regex seems to work:

/(<(?!\/)[^>]+>)+(<\/[^>]+>)+/

See a live demo with your example.

Solution 2:

Use jQuery and parse all children. For each child you have to check if .html() is empty. If yes -> delete the current element (or the parent if you want) with .remove().

Do for each string:

var appended = $('.yourparent').append('YOUR HTML STRING');

appended.children().each(function () 
{
    if(this.html() === '')
    {
        this.parent().remove(); 
    }
});

This will add the items first and delete, if there are empty children.

Post a Comment for "Regex To Remove Empty Html Tags, That Contains Only Empty Children"