Вопрос

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!

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top