0

Why doesnt .length work

<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> <p>hi</p> <p>hello</p> <p>hi</p> <script> var arr = document.getElementsByTagName("p").length; for (var x = 0; x < arr.; x++) { arr[x].innerHTML = "Hi there"; } </script> Why doesnt the second method work? Is there a limit on the number of methods you can add on a single object?

31st May 2018, 2:45 PM
IZzZI
IZzZI - avatar
6 ответов
+ 1
Hi IZzZI I think you want this <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> there is no length method on get element by tag name. the length method belongs to array
31st May 2018, 3:27 PM
Mike Choy
Mike Choy - avatar
0
remove the middle </script>
31st May 2018, 3:30 PM
Calviղ
Calviղ - avatar
0
Yes that way works but why doesn't document.getElementByTagName("p").length; work? What is wrong
31st May 2018, 3:31 PM
IZzZI
IZzZI - avatar
0
Calvin What do you mean?
31st May 2018, 3:32 PM
IZzZI
IZzZI - avatar
0
see my updated answer
31st May 2018, 3:32 PM
Mike Choy
Mike Choy - avatar
0
remove the middle </script> you would see both methods are working. JavaScript tag should be put after all the html code at right before closing body tag.
31st May 2018, 3:33 PM
Calviղ
Calviղ - avatar