HierarchyRequestError when modifying DOM in Windows Metro application

sth picture sth · Jul 3, 2012 · Viewed 11.6k times · Source

I'm building a Windows Metro application using Javascript and HTML and it crashes with a HierarchyRequestError:

Exception was thrown but not handled in user code at line 11, column 9 in ms-appx://21706d2f-b81e-47ef-9ebb-37de36c7a258/js/default.js
0x800a139e - JavaScript runtime error: HierarchyRequestError

At the line that throws the error I'm doing some simple DOM manipulation and try to insert a node I created into the document:

function insertData(hnode) {
    document.querySelector('#datanode').appendChild(hnode);
}

Why would this fail with such an error?

Answer

sth picture sth · Jul 3, 2012

A HierarchyRequestError is thrown when you try to insert undefined, or some other invalid value, into the DOM.

In the function in the question, hnode is probably undefined, for example because insertData() was called without parameters.

To debug a situation like this and find out which call to insertData() is the problem, a conditional breakpoint in Visual Studio can be used. If you set a breakpoint, right-click on it and choose "Condition...". A condition like hnode === undefined can be used to break on just the interesting cases.