Reputation: 41624
just wondering if there was a way to remove an html comment using jquery.
<!-- <div id="main">Some text </div> -->
thanks
Upvotes: 19
Views: 23473
Reputation: 331
I faced the errors with when script tried to access an IFrame content. Here is a modified version which is skipping IFrames:
$('*')
.filter((idx, el) => !(el instanceof HTMLIFrameElement))
.contents()
.each(() => {
try {
if(this.nodeType === Node.COMMENT_NODE) {
$(this).remove();
}
} catch (e) {
console.error(e);
}
});
Upvotes: 0
Reputation: 322502
Try this:
$('*').contents().each(function() {
if(this.nodeType === Node.COMMENT_NODE) {
$(this).remove();
}
});
EDIT: This removes the elements from the DOM. Browsers often store a copy of the original page source that is accessible through a menu item. This doesn't get updated.
If you want to hide your comments, you could always insert your entire HTML markup (with comments) into the DOM using javascript. The javascript could, of course, be viewed, but it is a step removed from the first place people would look.
Upvotes: 45
Reputation: 9041
This may be a slightly hacky way, but it worked an absolute treat for me.
It makes use of the split() function.
Firstly
codeWithComments = $("*yourelementhere*").html();
var withoutComments = codeWithComments.split('-->');
$("*yourelementhere*").html(withoutComments[withoutComments.length-1]);
This will replace the HTML of the given element with the code directly after the last '-->' this of course assumes that you only have one set of comments in the given element. You could split on the last line of the comment to get an exact match.
Worked for me, might not work in all cases.
Upvotes: 0
Reputation: 1444
Not that I know of. But I don't understand what the use of it would be. A comment will only be seen if you view the pagesource, and most (if not all) browsers that have a view source option will by default give you the source before javascript loading.
Upvotes: 0
Reputation: 4498
I'm almost certain comments aren't actually part of the DOM. They're part of the original HTML code, but when browsers convert it to the DOM, they get stripped as they serve no purpose for rendering.
Upvotes: -8