+ 2

Cannot read property 'length' of undefined

<html> <body> <div class="demo"> <p>some text</p> <p>some other text</p> </div> <script> var a = getElementsByClassName("demo"); var arr = a.childNodes; for(var x=0;x<arr.length;x++) { arr[x].innerHTML = "new text"; } </script> </body> </html>

21st Dec 2017, 4:55 AM
Mohamed Kalith
Mohamed Kalith - avatar
5 Réponses
+ 4
getElementsByClassName("demo") returns an array. You want to access the first element in this array since there is only 1 returned. You also need to add document object as a prefix Try: var a = document.getElementsByClassName("demo")[0];
21st Dec 2017, 5:12 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
in your code a global error is used, you use an undefined "demo" tag, probably you wanted to write document.getElementById ("Your id");
21st Dec 2017, 4:49 AM
James16
James16 - avatar
+ 2
Because you only have 1 element with the class "demo". If you had more you'd need to access each individually, usually in a for loop.
21st Dec 2017, 6:45 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
still not working?
21st Dec 2017, 4:55 AM
Mohamed Kalith
Mohamed Kalith - avatar
0
@ChaoticDawg why only returning 1 ?
21st Dec 2017, 6:42 AM
Mohamed Kalith
Mohamed Kalith - avatar