Why does the getElementsByTagName return undefined when processed by a for loop? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why does the getElementsByTagName return undefined when processed by a for loop?

I’m trying to pick three tag values from the HTML by using the getElementsByTagName, assign them to an array called getItems and assign each value of the array to the variable called array by using a for loop. But the browser returned undefined. I tried to remove the double quotes when I declared the array variable but it didn’t work either. Can anyone please help? I’m new to JavaScript, so an answer with an explanation will be a great help for me. https://code.sololearn.com/W0fOKBT0eLtT/?ref=app

17th Feb 2021, 10:08 PM
Moshe Schnitzler
Moshe Schnitzler - avatar
2 Answers
+ 3
Yoh are going for the childNodes of each element "p" while they don't exist. Also i believe there is no property like nodeValue (not sure) . And still if there was nodeValue property , it wudn't work as childNodes itself is a list of nodes including textNodes as well. But here is how you can get value inside each element. getItems[i].innerText
17th Feb 2021, 10:17 PM
Abhay
Abhay - avatar
+ 1
getElementsByTagName returns an HTMLCollection which doesn't have the [ i ] operator, because it's not an Array. Instead you have to access the items in the array-like collection using the item() method. Or you can use the spread operator (...): let getItems = ...ByTagName("p"); let str = ""; for (let item of [...getItems]) { array += item.textContent; } Don't need to use .childNodes.nodeValue
18th Feb 2021, 1:49 AM
Zeke Williams
Zeke Williams - avatar