EN
HTML - getting all paragraphs using JavaScript returns additional undefined paragraph
1
answers
3
points
I am trying to print all <p> elements from my web page using custom printParagraphs() function.
I have 4 paragraphs in my HTML code but the function returns 5, the last one is undefined.
Why is that so?
My code:
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
function printParagraphs() {
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
for (var i = 0; i < paragraphs.length; ++i) {
console.log(paragraphs[i].outerHTML);
}
}
window.addEventListener('load', function() {
console.log(printParagraphs());
});
</script>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
</html>
Can you explain to me why is there a 5th undefined paragraph?
1 answer
3
points
There's no 5th paragraph in your code.
You need to consider if you want to print paragraphs inside printParagraphs() function or return the paragraphs from the function and then print them using console.log() call. In your source code the function doesn't return any value so by default it is undefined. Finally the last console.log() call prints undefined according to returned value.
There are two ways to fix it:
- unwrap the
printParagraphs()with theconsole.log()inside windowloadevent, - use
returnstatement in yourprintParagraphs()function.
Practical examples
ad.1
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
function printParagraphs() {
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
for (var i = 0; i < paragraphs.length; ++i) {
console.log(paragraphs[i].outerHTML);
}
}
window.addEventListener('load', function() {
printParagraphs();
});
</script>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
</html>
ad.2
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<script>
function findParagraphs() {
var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
var result = [];
for (var i = 0; i < paragraphs.length; ++i) {
result.push(paragraphs[i].outerHTML);
}
return result;
}
window.addEventListener('load', function() {
console.log(findParagraphs());
});
</script>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</body>
</html>
0 comments
Add comment