You can filter comments out, but it is not easy. I will show you how you can filter them on the first level, which is easy, but if they are nested within other tags, then you need to do additional logic.
The key is to .contents()
to get all the nodes within. This includes comment nodes. Then you can filter the comment nodes out by comapring against nodeType.
So it would be something like this:
$(".welcome-msg").contents().filter(function() {
return this.nodeType != 8;
}).appendTo("<div>").parent().html();
That will work for
<div class=".welcome-msg">
<!--Comment --><span>hello</span>
</div>
But not for
<div class=".welcome-msg">
<span><!--Comment -->hello </span> world
</div>
You would need to iterate through all tags recursively and then it will work for everything.
With regular expressions you would need to be careful about <script>
tags and <style>
tags.
Here is the jsfiddle
Update (Recursive filter)
Doing it recursively is actually quite easy:
http://jsfiddle.net/xYR5p/3/
Made an entire plugin for it:
$.fn.removeComments = function() {
this.contents().filter(function() {
return this.nodeType == 8;
}).remove();
this.children().each(function() {
$(this).removeComments();
});
return this;
};
console.log($(".welcome-msg").clone().removeComments().html());