EN
JavaScript - iterate over all paragraphs on web page to get their text content
0 points
In this article, we would like to show you how to iterate over all paragraphs on web page to get their textContent using JavaScript.
Quick solution:
xxxxxxxxxx
1
function getParagraphsText() {
2
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
3
var text = [];
4
for (var i = 0; i < paragraphs.length; ++i) {
5
text.push(paragraphs[i].textContent);
6
}
7
return text;
8
}
In this example, we use querySelectorAll()
method to get the collection of all paragraphs (p
elements) on the web page. Then we iterate through the collection to get each paragraph textContent
value and save it inside text
variable.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Paragraph 1</p>
5
<p>Paragraph 2</p>
6
<script>
7
8
function getParagraphsText() {
9
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
10
var text = [];
11
for (var i = 0; i < paragraphs.length; ++i) {
12
text.push(paragraphs[i].textContent);
13
}
14
return text;
15
}
16
17
18
// Usage example:
19
20
window.addEventListener('load', function() {
21
console.log(getParagraphsText());
22
});
23
24
</script>
25
<p>Paragraph 3</p>
26
<p>Paragraph 4</p>
27
</body>
28
</html>
Note:
The
getParagraphsText()
function needs to be executed after windowload
event or at the end of the script to make sure that all items are loaded before the function execution.