removing empty nodes with jQuery

Sometimes you have empty html tags on your code tree and no matter what you try in your cms / php, you can’t avoid them to appear in the rendered html.

But even then you can remove empty instances through some compact jQuery snippets – here are some examples that show how to remove empty links and empty image tags from the html document…

This is how to remove an empty image tag, that generates an error:

 $("img").error(function(){
     $(this).remove();
 });

This is how to remove a link tag that generates an error:

 $("a").error(function(){
     $(this).contents().unwrap();
 });

This is how to hide the parent tag, if the child tag “inscriptions” is empty:

 $("inscriptions:empty").parent().hide();

This is how to remove ’empty’ links that point to a directory instead of a page:

 $("a").each(function() {
     var href = $(this).attr("href");
     if(href == '/node/') { // or anything else you want to remove...
         $(this).contents().unwrap();
     }
 });

This is how to remove ’empty’ image tags that point to non-existing images:

 $("img").each(function() {
     var src = $(this).attr("src");
     if(src == '/images/-thumb.JPG') { // or anything else you want to remove...
         $(this).remove();
     }
 });

See also:

And here’s some related links:

Leave a Reply

Your email address will not be published. Required fields are marked *