document.getElementById() doesn't work?

html, javascript

Solution

Put your script AFTER the actual element, otherwise by the time your javascript code runs, there's not yet such element in the DOM.

<html>
    <body>
        <input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
        <script>
            var x = document.getElementById('btn1');
            alert(x);
        </script>
    </body>
</html>

Alternatively put your script in a DOM ready event to ensure that the DOM is fully loaded by the browser before attempting to manipulate it:

<html>
    <body>
        <script>
            window.onload = function() {
                var x = document.getElementById('btn1');
                alert(x);
            };
        </script>
        <input type="button" id="btn1" value="Clickme" onclick="alert('1')" />
    </body>
</html>

Problem

No much to say, ``` <html> <body> <script> var x = document.getElementById('btn1'); alert(x); </script> <input type="button" id="btn1" value="Clickme" onclick="alert('1')" /> </body> </html> ``` The alert message is `null` instead of a message contain details of the object or something like that. What is the problem?

Original source

Related problems