Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript code not work in HEAD tag

My webpage has the following code:

<html>
<head>
    <title>This is test Page</title>

     <script language="javascript" type="text/javascript">

         document.getElementById("msg1").innerHTML = document.URL.toString();
        </script>

</head>
<body>

    <div class="sss">
        <p id="msg1"></p>
    </div>


</body>
</html>

As you now at the time the script executes the div doesn't exist but I want to put my JavaScript code only In the <head> tag and I won't put it in middle of HTML code.

But this code only works when I put the <script> tag after the <div> tag. I use VS2010 and firefox 19.0.1

Is there anyway to put code in <head> tag?

like image 767
AminM Avatar asked Mar 28 '13 06:03

AminM


2 Answers

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

Tharsan


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
}
like image 37
Abbas Rahimi Avatar answered Sep 22 '22 19:09

Abbas Rahimi