Is there a DOM API for querying comment nodes?

后端 未结 2 419
既然无缘
既然无缘 2020-12-19 02:24

I have a document with a debugging comment in it that looks like this:


Is there a way to query the DOM to a

相关标签:
2条回答
  • 2020-12-19 02:52

    The nodeType core property allows you to differentiate between types of nodes. In this particular case, 8 represents comments. As they have no selector, you'll need to loop through their parent to get them (which sucks, I know). The following code filters them out for you:

    $("*").contents().filter(function(){
        return this.nodeType == Node.COMMENT_NODE;
    })
    

    And my own jQuery-less version, because some people don't have it:

    function getAllComments() {
        var t = [],
            recurse = function (elem) {
                if (elem.nodeType == Node.COMMENT_NODE) {
                    t.push(elem);
                };
                if (elem.childNodes && elem.childNodes.length) {
                    for (var i = 0; i < elem.childNodes.length; i++) {
                        recurse(elem.childNodes[i]);
                    };
                };
            };
        recurse(document.getElementsByTagName("html")[0]);
        return t;
    };
    

    If you'd like to search on a specific node, re-bind the document.getElementsByTagName call to a variable of your choosing.

    Edit: fiddle to demonstrate the use, done by Jason Sperske!

    0 讨论(0)
  • 2020-12-19 03:19

    There's the TreeWalker APIs:

    var tw = document.createTreeWalker(document, NodeFilter.SHOW_COMMENT, null, null),
        comment;
    while (comment = tw.nextNode()) {
        // ...
    }
    

    This isn't supported by IE8 and lower.

    T.J. in the comments provided a link to the specs. I kind of always use just TreeWalkers, but in your case a NodeIterator is fine too.

    0 讨论(0)
提交回复
热议问题