EN
JavaScript - find all HTML comments
3 points
In this article, we would like to show you how to find all HTML comments using JavaScript.
Quick solution:
xxxxxxxxxx
1
function filterNone() {
2
return NodeFilter.FILTER_ACCEPT;
3
}
4
5
function findComments(element) {
6
var comments = [];
7
var iterator = document.createNodeIterator(element, NodeFilter.SHOW_COMMENT, filterNone, false);
8
while (true) {
9
var node = iterator.nextNode();
10
if (node == null) {
11
break;
12
}
13
comments.push(node.nodeValue);
14
}
15
return comments;
16
}
17
18
19
// Usage example:
20
21
var comments = findComments(document.body); // finds all comments inside body and nested elements
In this example findComments()
function returns all comments located inside the indicated element (in our case document.body
). The function uses embeded node iterator.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<!-- Comment 1 -->
5
<!-- Comment 2 -->
6
<script>
7
8
function filterNone() {
9
return NodeFilter.FILTER_ACCEPT;
10
}
11
12
function findComments(element) {
13
var comments = [];
14
var iterator = document.createNodeIterator(element, NodeFilter.SHOW_COMMENT, filterNone, false);
15
while (true) {
16
var node = iterator.nextNode();
17
if (node == null) {
18
break;
19
}
20
comments.push(node.nodeValue);
21
}
22
return comments;
23
}
24
25
26
// Usage example:
27
28
window.addEventListener('load', function() {
29
console.log(findComments(document.body));
30
});
31
32
</script>
33
<!-- Comment 3 -->
34
<!-- Comment 4 -->
35
</body>
36
</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.