2

Consider this JS (which is run at the end of the body and causing an error)

(function(){
    "use strict";

    var div = document.getElementById("hook"),
        ul = div.firstElementChild,
        last_li = ul.lastElementChild;

    alert(div) // alerts "Uncaught TypeError: Cannot read property 'children' of undefined"  

})();

I then removed the commas and added the var keyword, but received a similar error (it's not the HTML):

(function(){
    "use strict";

    var div = document.getElementById("hook");
    var ul = div.firstElementChild;
    var last_li = ul.lastElementChild;

    alert(div) // alerts "Uncaught TypeError: Cannot read property 'lastElementChild' of undefined " 

})();

The only way it works is by adding the alert() statement directly after the div assignment. I'm assuming this has relevance to variable hoisting but am not experienced enough to know for sure.

Can someone give a quick synopsis of variable hoisting and what may be going on here? Thanks!

3
  • Can you show your entire page? Your code works fine for me: jsfiddle.net/MDRrL Commented Jan 13, 2014 at 17:38
  • 1
    You can just Google hoisting, but here's a description: adequatelygood.com/JavaScript-Scoping-and-Hoisting.html There doesn't seem to be any variable hoisting going on here, and the code works just fine as is for me. Commented Jan 13, 2014 at 17:40
  • Technically hoisting IS going here BUT it isn't having an effect on anything here. Commented Jan 13, 2014 at 17:43

1 Answer 1

3

This is not hoisting.

What's happening here is the following:

(function(){
    "use strict";

    // this returns an element otherwise the next line would not work
    // that means the element is found in the DOM
    var div = document.getElementById("hook"), 
        // this returns the value `undefined` or `null` 
        ul = div.firstElementChild,
        // this is a TypeError, since `ul` is undefined
        last_li = ul.lastElementChild;

    alert(div) // we never actually get to this line
})();

It's possible that the Element you have has no Elements in it (maybe just text nodes?)

Here is a fiddle reproducting the issue.

Here is a fiddle where it works.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I did have children elements but they were commented out -- after removing the comments it works as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.