user3643415
user3643415

Reputation: 1

WinJS DOM-Loading

I've programmed an WinJS-App (Metro-App) for Windows 8. The problem is, that I get "nullpointer exception" as soon as I try to access a DOM(HTML)-Element like a div. The problem code is this:

WinJS.UI.Pages.define("/pages/home/home.html", {
    ready: function (element, options) {
        document.getElementById("inhalt").innerHTML = "test"; // causes NullpointerException
    }
});

But when I do this instead, there is no problem. But I don't want to wait 3 seconds each time.

WinJS.UI.Pages.define("/pages/home/home.html", {
    ready: function (element, options) {
        window.setTimeout(function() { document.getElementById("inhalt").innerHTML = "test"; }, 3000);
    }
});

Why is NullPointerException thrown and how can I fix it?

Upvotes: 0

Views: 113

Answers (1)

Xirzec
Xirzec

Reputation: 151

This is probably because ready() is called before your page is parented into the DOM, so document.getElementById can't find it. You are being passed the root element in the ready function, so you can instead do:

element.querySelector('#inhalt').innerHTML = "test";

And that should work. It's a best practice for pages to not use ids inside of pages though, so just change it to a class class="inhalt" and make it element.querySelector('.inhalt').

Upvotes: 1

Related Questions