Confused about this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Confused about this code

<p>hi</p> <p>hello</p> <p>hi</p> <script> var arr = document.getElementsByTagName("p"); for (var x = 0; x < arr.length; x++) { arr[x].innerHTML = "Hi there"; } </script> The for loop. So the loop declares x as its variable, and where x is less than the length of arr, it increases by 1. What is the length of arr referring to? Is the number 3? Would it be easier to do where x less than 3? Thanks a lot.

12th Jul 2019, 8:57 PM
Princess N
Princess N - avatar
4 Answers
+ 3
I'm new to Javascript too, but this is my understanding of the code. arr is an array which contains the contents of each p tag pair arr.length is the number of elements in the array which in this case is 3 as there are 3 p tag pairs x is a variable which is used to count the number of times the loop has completed
12th Jul 2019, 9:04 PM
Vince Warner
Vince Warner - avatar
+ 2
So, the getElementsByTagName gets all of them with the specified tag and puts them into a list? Thanks!
12th Jul 2019, 9:15 PM
Princess N
Princess N - avatar
+ 2
I guess an array is sort of like a list I prefer to think of it as a row of containers, where the number of containers is equal to the number of things you need to store. Each container is labelled from zero up to the number of items stores minus one. It's then easy to use a programming language to grab any information from the array simply by referencing it's container number. I'm not aware of any programming language that doesn't use arrays, although I'm sure somebody else will know of one.
12th Jul 2019, 9:27 PM
Vince Warner
Vince Warner - avatar