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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With