Languages
[Edit]
EN

JavaScript - find all HTML comments

3 points
Created by:
Savannah
559

In this article, we would like to show you how to find all HTML comments using JavaScript.

Quick solution:

function filterNone() {
    return NodeFilter.FILTER_ACCEPT;
}

function findComments(element) {
    var comments = [];
    var iterator = document.createNodeIterator(element, NodeFilter.SHOW_COMMENT, filterNone, false);
    while (true) {
        var node = iterator.nextNode();
        if (node == null) {
            break;
        }
        comments.push(node.nodeValue);
    }
    return comments;
}


// Usage example:

var comments = findComments(document.body); // finds all comments inside body and nested elements

 

Practical example

In this example findComments() function returns all comments located inside the indicated element (in our case document.body). The function uses embeded node iterator.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <!-- Comment 1 -->
  <!-- Comment 2 -->
  <script>

    function filterNone() {
        return NodeFilter.FILTER_ACCEPT;
    }

    function findComments(element) {
        var comments = [];
        var iterator = document.createNodeIterator(element, NodeFilter.SHOW_COMMENT, filterNone, false);
        while (true) {
            var node = iterator.nextNode();
            if (node == null) {
                break;
            }
            comments.push(node.nodeValue);
        }
        return comments;
    }


    // Usage example:

    window.addEventListener('load', function() {
        console.log(findComments(document.body));
    });

  </script>
  <!-- Comment 3 -->
  <!-- Comment 4 -->
</body>
</html>

Note:

In the example we use addEventListener() method to execute the functon after all elements are loaded. Otherwise it wouldn't find the comments that are after the <script> tag.

 

See also

  1. JavaScript - load events order for window, document, dom, body and elements

References

  1. Document Object Model Traversal

Alternative titles

  1. JavaScript - get all HTML comment nodes
  2. JavaScript - get all HTML comments
  3. JavaScript - find all HTML comment nodes
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join