是否可以通过JavaScript来引用注释元素/块?

问题描述:

这听起来有点疯狂,但我想知道是否可能引用注释元素,以便我可以动态地用JavaScript替换其他内容。

This sounds a little crazy, but I'm wondering whether possible to get reference to comment element so that I can dynamically replace it other content with JavaScript.

<html>
<head>
</head>
<body>
<div id="header"></div>
<div id="content"></div>
<!-- sidebar place holder: some id-->
</body>
</html>

在上面的页面中,我可以参考注释块并将其替换为本地存储中的一些内容?

In above page, can I get reference to the comment block and replace it with some content in local storage?

我知道我可以有一个div place holder。只是想知道它是否适用于注释块。
谢谢。

I know that I can have a div place holder. Just wondering whether it applies to comment block. Thanks.

var findComments = function(el) {
    var arr = [];
    for(var i = 0; i < el.childNodes.length; i++) {
        var node = el.childNodes[i];
        if(node.nodeType === 8) {
            arr.push(node);
        } else {
            arr.push.apply(arr, findComments(node));
        }
    }
    return arr;
};

var commentNodes = findComments(document);

// whatever you were going to do with the comment...
console.log(commentNodes[0].nodeValue);