EN
JavaScript - find all paragraphs on web page
0 points
In this article, we would like to show you how to find all paragraphs on web page using JavaScript.
Quick solution:
xxxxxxxxxx
1
document.querySelectorAll('p');
In this example, we use querySelectorAll()
method to get the collection of all paragraphs (p
elements) on the web page.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<p>Paragraph 1</p>
5
<script>
6
7
function findParagraphs() {
8
return document.querySelectorAll('p'); // finds all paragraphs
9
}
10
11
12
// Usage example:
13
14
window.addEventListener('load', function() {
15
console.log([findParagraphs()]);
16
});
17
18
</script>
19
<p>Paragraph 2</p>
20
</body>
21
</html>
Note:
The
findParagraphs()
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.