Vladimir Goncharuk
Vladimir Goncharuk

Reputation: 362

document.body.getElementById is not a function

Happy New Year to all. Today, I encountered a very strange thing.

TypeError: document.body.getElementById is not a function

Several times I have checked all the characters, everything must be true

   <!DOCTYPE html>
    <html>
    <head>
        <title>Test</title>
        <meta charset="utf-8">
    </head>
    <body>
        <script type="text/javascript">
        function addElem()
        {
        var number=document.body.getElementById("number");
        }
        </script>
        <input type="text" id="number">
        <br>
        <button onclick="addElem()">Add</button>


 </body>
   </html>

Why do I get this error?

Upvotes: 1

Views: 9356

Answers (3)

Vishal Rana
Vishal Rana

Reputation: 21

You cannot have a getElementById() method for the document.body element

Use document.getElementById() instead!

Upvotes: 1

bobo
bobo

Reputation: 193

That's because document.body is an element. Elements do not have a getElementById() method since ids are unique and using it relative to specific element would be useless.

Upvotes: 6

mike510a
mike510a

Reputation: 2168

use document.getElementById() not document.body.getElementById() to achieve the desired effect

Upvotes: 9

Related Questions