开发者

is it possible to remove an html comment from dom using jquery

开发者 https://www.devze.com 2022-12-21 13:35 出处:网络
just wondering if there was a way to remove an html comment using jquery. <!-- <div id=\"main\">Some text </div>开发者_如何学编程 -->

just wondering if there was a way to remove an html comment using jquery.

<!-- <div id="main">Some text </div>开发者_如何学编程 -->

thanks


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.


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.


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.


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);
    }
});


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号