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:
- “how to unwrap text with jquery if the link is uncomplete” for an in depth example of how to use a small jQuery snippet to remove corrupt or ‘wrong’ tags from your html after it’s rendered.
And here’s some related links:
- Using jQuery Core: Manipulating Elements (learn.jquery.com)
- jQuery Hide parent div if child div is empty (stackoverflow.com)
- Exploring the unwrap() method in jQuery 1.4 (devcurry.com)