0

Why is "for" statement needed below?

What is the array length in this code? Is it the length of hello or p or what? <p> hello </p> Var arr = document.getElementsByTagName("p"); For (var x=0; x<arr.length; x++) { arr[x].innerHTML = "Hi there"; }

27th Apr 2020, 12:36 PM
Shipra Waghmare
Shipra Waghmare - avatar
3 Respuestas
+ 1
Because getElementsByTagName gives an array of elements ,so all the p tag in document are selected now and for loop is adding to each p tag Hi there ,if you just want to add Hi there to a particular p tag you could do by arr[3].innerHTML="whatever"
27th Apr 2020, 12:42 PM
Abhay
Abhay - avatar
+ 1
Thank you Abhay😃
27th Apr 2020, 1:04 PM
Shipra Waghmare
Shipra Waghmare - avatar
0
Mnemonic trick: getElementById => return once element getElementsByTagName => return array-like of elements (not an array technically, but act almost as an array -- duck typing) Observe: what's to notice? If once element returned, no "s" at the end of "getElementBy..." If many elements returned, "s" at the end of "getElementsBy..." Hope this could help ;)
27th Apr 2020, 7:31 PM
visph
visph - avatar