Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementById() doesn't work? [duplicate]

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?

like image 886
Billie Avatar asked Dec 07 '13 08:12

Billie


2 Answers

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>
like image 180
Darin Dimitrov Avatar answered Sep 21 '22 19:09

Darin Dimitrov


You need to run the javascript after the html s read/rendered...

Try this instead:

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

Or you can add a window load function so the script only runs after the page has loaded. Like:

<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>
like image 20
Sergio Avatar answered Sep 21 '22 19:09

Sergio