Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementsByTagName doesn't work. How can I get the length of NodeList of body?

Tags:

javascript

dom

I want to get the length or item of body tag. But, It seems getElementsByTagName doesn't work in terms of NodeList. How can I do that?

 <script type=text/javascript>
 var b = document.getElementsByTagName('body');                                                                                                                            
 console.log(b);         // <body>...</body>
 console.log(b.length);  // 0    
 console.log(b[0]);      // undefined
 console.log(b.item(0)); // null
 </script>

Thanks.

[Edit] I added entire body.

<html>
<head>
<script type=text/javascript>
 var b = document.getElementsByTagName('body');                                                                                                                            
 console.log(b);         // <body>...</body>
 console.log(b.length);  // 0    
 console.log(b[0]);      // undefined
  console.log(b.item(0)); // null
</script>
</head>
<body>
<div id='test'>
<h2>Hello</h2>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
</body>
</html>
like image 303
kinakomochi Avatar asked Dec 07 '25 08:12

kinakomochi


1 Answers

Place the script at the end of the page, or place it in a function and call it after the entire page has loaded.

like image 142
Valentin D Avatar answered Dec 08 '25 20:12

Valentin D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!