shaijuelayidath Posted September 4, 2012 Share Posted September 4, 2012 <!DOCTYPE html><html><head></head> <body> <p id="demo">A Paragraph</p> <script type="text/javascript">document.getElementById("demo").innerHTML="My First JavaScript";</script> </body></html> The script above is one of the basic manipulation of html element with Javascript. But when I place this script in the <head> tag, it is not working, but the tutorials says Javascript will work from both <head> and <body>. Can anybody clarify this ? Link to comment Share on other sites More sharing options...
dsonesuk Posted September 4, 2012 Share Posted September 4, 2012 That reference to 'demo' won't work in head, because element with id ref 'demo' has not been rendered yet! that is why it works below that element, its been created and so can be referenced, place you code within window.onload=function() {//place code here} and then place this in the head, this function is only trigged when the page has fully loaded. Link to comment Share on other sites More sharing options...
Krewe Posted September 4, 2012 Share Posted September 4, 2012 Similarly, jQuery needs the same process Dsone said. Except different format: Long-Hand: $("document").ready(function (){// Place Code Here}); Short-hand: $(function (){//Place code here}); Both of those will only run once the page has loaded. Assuming you are using the JavaScript library jQuery.I just wanted to give you a heads up on this before you start using it. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now