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:
function getParagraphsText() {
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
var text = [];
for (var i = 0; i < paragraphs.length; ++i) {
text.push(paragraphs[i].textContent);
}
return text;
}
Practical example
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.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
function getParagraphsText() {
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
var text = [];
for (var i = 0; i < paragraphs.length; ++i) {
text.push(paragraphs[i].textContent);
}
return text;
}
// Usage example:
window.addEventListener('load', function() {
console.log(getParagraphsText());
});
</script>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
</html>
Note:
The
getParagraphsText()function needs to be executed after windowloadevent or at the end of the script to make sure that all items are loaded before the function execution.