My webpage has the following code:
This is test Page
Your script uses dom element and must run after the dom loaded.
Wrap your code in a function and call it after dom loaded
function myfunc(){
//code here
}
window.onload = myfunc();
Michael Geary is right, in order to execute your code, I'd use jQuery library (a de-facto standard in JS development) and utilize the DOM ready event. This will ensure the code in the handler will execute once DOM is fully loaded.
<script>
$(function(){
$('#msg1').html(document.URL.toString());
});
</script>
I recommend to to use addEventListener
like this:
<script language="javascript" type="text/javascript">
document.addEventListener("DOMContentLoaded",() => {
document.getElementById("msg1").innerHTML = document.URL.toString();
});
</script>
Your script relies on the DOM being ready, so you need to execute that function call only after the DOM is ready.
<script language="javascript" type="text/javascript">
window.onload = function() {
document.getElementById("msg1").innerHTML = document.URL.toString();
}
</script>
Your script uses a DOM element and therefore must run after the DOM is loaded. You can do that by using this function:
$(document).ready(function(){
//code here
}
The various tags in your HTML page are loaded and processed in the order in which they appear on the page. Your <script>
tag is executed immediately when it is parsed in the <head>
. This is before the <body>
and the elements inside the <body>
are parsed. So, the script tries to reference an element that is not defined at the time it is executed.