+ 1
Clarification on a challenge
Hello, I just finished completing a challenge consisting of an html element: <p>hi</p> And a script file: var p,b; p=document.getElementByTagName(‘p’); b = document.createTextNode(‘there’); p[0].appendChild(b); On the fourth line of JS, how is it that the array comes into play? Thanks for any help you can provide with this solution.
5 ответов
+ 3
The getElementsByTagName() function returns a collection, you can see it as an array I guess, of elements with the given tag.
Here it just happens that there is only one element with the tag p. Nonetheless the var p still contains a collection; it just that this collection only has one element in it. So to access it we must do p[0].
You can read the docs to learn more about the function.
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
+ 2
The p tag by itself is not an array in the DOM. But when we ask for p tags elements using getElementsByTagName('p') it returns us all p tags present in an array
I just made this code to play a bit with getElementsByTageName and understand it better. You can do append operations and other sorts of operations using the result you got from using get......TagName() to see how they changes the elements in your DOM. And, you can uncomment the last two lines to see how your DOM is modified on live as well.
https://code.sololearn.com/WJ0KdD1uWtCy/?ref=app
+ 2
You're very welcome!
+ 1
Perfect! thanks man
0
ok so the p tag would be an array in the DOM, thus index of 0 and then append the b variable - ‘there’. So it would be adding index of 1 to that tag, would I possibly be right on that assumption? BTW, thanks for the link!