EN
JavaScript - find all text nodes on web page
0 points
In this article, we would like to show you how to find all text nodes on web page using JavaScript.
In this example, we create a reusable arrow function that walks through all text nodes of the passed node
element applying filter
function to them. In usage example section we also create filter that excludes all empty text nodes. At the end, we call the walkTextNodes()
function on window load
event.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<h1>Header</h1>
5
<div>Div</div>
6
<script>
7
8
function walkTextNodes(node, filter) {
9
var result = [];
10
function execute (node) {
11
var child = node.firstChild;
12
while (child) {
13
switch (child.nodeType) {
14
case Node.TEXT_NODE:
15
if (filter(child)) {
16
result.push(child);
17
}
18
break;
19
case Node.ELEMENT_NODE:
20
execute(child);
21
break;
22
}
23
child = child.nextSibling;
24
}
25
}
26
if (node) {
27
execute(node);
28
}
29
return result;
30
}
31
32
33
// Usage example:
34
35
var container = document.body;
36
37
function filter(node) { // this filter removes text nodes that contains white characters only
38
return /^(\s|\n)+$/gi.test(node.data) ? false : true;
39
};
40
41
window.addEventListener('load', function() {
42
var nodes = walkTextNodes(container, filter);
43
for (var i = 0; i < nodes.length; ++i) {
44
console.log(nodes[i].data);
45
}
46
});
47
48
</script>
49
<p>Paragraph</p>
50
<span>Span</span>
51
</body>
52
</html>
Note:
The
walkTextNodes()
function needs to be executed after windowload
event or at the end of the script to make sure that all elements are loaded before the function execution.
Note:
The
<script>
element content is being displayed because the interpreter treats it a text node.