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"; }
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"
+ 1
Thank you Abhay😃
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 ;)