3

I am new to Java script. I am practicing code.When i put my code in the head section, then i get element null, and when i put it inside body, but before element, then i also get null, but if i put it inside body, but after element then i get the element. I want to ask why i am getting null in case of the first two cases. Here is my code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <script type="text/javascript" src="js/attributes.js"></script>   // null

    </head>
    <body>

        <script type="text/javascript" src="js/attributes.js"></script>  // null
        <a id="braingialink"
           onclick="return showAttributes();"
           href="http://www.braingia.org" >Steve Suehring's Web Site
        </a>

        <script type="text/javascript" src="js/attributes.js"></script>   // ok

</body>

Here is my javascript

var a1 = document.getElementById("braingialink");     //get null in first two cases
window.alert(a1.getAttribute("href"));
a1.setAttribute("href", "www.google.com");
window.alert(a1.getAttribute("href"));

function showAttributes() {

    var e = document.getElementById("braingialink");
    var elementList = "";

    for (var element in e) {

        /**
         * Sometimes, especially when first programming with JavaScript, you might not know what
         * attributes are available for a given element. But you don’t have to worry about that, because
         * of a loop that calls the getAttribute() method.
         */
        var attrib = e.getAttribute(element);
        elementList = elementList + element + ": " + attrib + "\n";

    } //end of for()

    alert(elementList);

} //end of function showAttributes

And also tell me, placing <script type="text/javascript" src="js/attributes.js"></script>

after the a element, is the same as i write script in the script tag , like

<a href="http://www.braingia.org" id="braingialink">Steve Suehring's Web Site</a>
<script type="text/javascript">
    var a1 = document.getElementById("braingialink");
    alert(a1.getAttribute("href"));
    a1.setAttribute("href","http://www.microsoft.com");
    alert(a1.getAttribute("href"));
</script>

Are both things mean to same?

Thanks

Basit
  • 8,426
  • 46
  • 116
  • 196
  • Duplicate of [Where should I put – Herohtar Apr 28 '22 at 14:00

7 Answers7

5

The browser parses the document from top to bottom, and if it encounters a <script> block (whether inline script or inclusion of an external JS file) it runs that JavaScript before parsing any more of the document. If that particular code block tries to refer to any elements it can only access the ones above it in the source, i.e., the ones already parsed.

The document.getElementById() method returns null if no element is found for the id you supply, so if you try to use it to access elements below it in the source they've not yet been parsed and can't be found.

The two most common practices to deal with this are:

  1. Put all of your script at the bottom of the <body> such that when it runs all of the elements will have been parsed.

  2. Create an "onload" handler, that is, define a function that will be run as soon as the document finishes loading. You can do this from a script block in the <head> - the JavaScript that defines the onload function is run immediately, but then the function is executed later after everything has loaded.

Following is the simplest way to do option 2:

window.onload = function() {
   var x = document.getElementById("x");
   // other element manipulation here
};

There is nothing stopping you doing 1 and 2 in the same document, along with throwing some <script> blocks in the middle of the document, but most people find it neater to keep all their code in the one spot.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • i want to ask when we use ``. Is this same as we write `window.onload = someFunction() {...};`. Like if i write a simple function in .js file, `function someFunction(){..}` and then use the line `` in my HTML, then it has the same effect as i include my .js file in the head section and in that .js i write `window.onload = someFunction() {...};`. Both are same ? – Basit Feb 09 '12 at 10:55
  • It's almost the same. `` set as an attribute in the html is like saying `window.onload = function() { something }`, that is, the code you put in the attribute doesn't have to call a function, it kind of has an implied function around it. Many people prefer not to mix their JavaScript into their html because it can be more of a headache to maintain. Note: you'll want to put quotes around JavaScript set in an html attribute. – nnnnnn Feb 09 '12 at 10:58
1

You're getting null in the head because the DOM has not loaded - your objects are nonexistent at that time. Use this:

window.onload = function () {
    // Your code
}

Oh and also take a look at the .ready() function of jQuery here. It would certainly help the headache later on.

Aram Kocharyan
  • 20,165
  • 11
  • 81
  • 96
  • When you use window.onload does this wait for all elements to be loaded before running the script or does it run as the page is loading?? – CSharpened Feb 09 '12 at 10:28
  • 1
    Yes, it will wait for everything to load. Refer to this page: http://makeagreatsite.com/javascript/how-execute-javascript-when-document-ready – Aram Kocharyan Feb 09 '12 at 10:29
  • so when we use scripts in head section or right after the body tag? It means that if you want to access any element in the HTML , then it is best to use scripts right before the closing body tag, as suggested by **Jannis M**. – Basit Feb 09 '12 at 10:32
  • Yes, I think that should work as well, but just for safety it's usually good practice to be certain. Also, you may want your js in a single file as it get longer. All it takes is to call a custom `init` function inside the `window.onload` and you're set. – Aram Kocharyan Feb 09 '12 at 10:50
  • 1
    There's no "should" about it, you can be certain that putting the code at the end _will_ work as effectively as using onload. Note that you can set `window.onload=...` from inside your external JS file, so you don't need an `init` function as well. If you're concerned about having multiple external JS files all needing to do something with `onload` then use `.addEventListener()` / `.attachEvent()` so that you can attach multiple (independent) handlers. – nnnnnn Feb 09 '12 at 10:56
  • yep, I agree with that. I find it cleaner using an init just so the onload function is shorter and I can call init at any time I need to. – Aram Kocharyan Feb 09 '12 at 10:58
1

Normally you should put script blocks inside the head tag. You can put them in the body tag if you have a special reason, for example to make the script load later because it comes from a slow server.

The reason that you can't access the element, is that the code runs before the browser has parsed the code for the element, so the element simply doesn't exist yet.

You use the load event to run the code after the document is loaded:

window.onload = function() {

  // here you put the code that needs to access the elements

}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

You need to understand how web browsers load resources into a page. Firefox -> Firebug add-on Net tab shows the timeline of how resources are loaded. If you are using jQuery or something like it (and you aught to) - then stick your code inside $(document).ready(function() { .. } - that will ensure the page has fully loaded.

Also, it's a good practise to to include your custom js last thing before </body> tag - that way page DOM would have loaded.

Have a read if you want to understand this deeper: http://www.goodreads.com/book/show/6438581-even-faster-web-sites and http://www.goodreads.com/book/show/1681559.High_Performance_Web_Sites

Val Redchenko
  • 580
  • 1
  • 8
  • 20
1

see http://www.w3schools.com/js/ and http://www.w3schools.com/js/js_whereto.asp

You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

sysop
  • 800
  • 2
  • 9
  • 18
0

Best would be right before the closing body tag, to not disturb the page loading and rendering at all! It's also recommended by google, for example for analytics snippet and also by facebook!

Jannis M
  • 745
  • 1
  • 4
  • 15
0

you get nulls because your script executes while the browser is still loading the page. Since the page might not yet have all elements rendered, you get nulls. you need to run the script when the page has finished loading. put your script in to the HEAD element, and invoke it on body's onload event.

akonsu
  • 28,824
  • 33
  • 119
  • 194