11

most javascript libraries contain lines similar to:

    var b = (a ? a.ownerDocument || a: 0).documentElement;

if a is null, what is (0).documentElement supposed to return?

4 Answers 4

4

From jQuery / Sizzle comments:

http://jsapi.info/jquery/1.7.2/jQuery.isXMLDoc

documentElement is verified for cases where it doesn't yet exist (such as loading iframes in IE - #4833)

So it's just cute syntax for returning undefined - this is a result of calling documentElement on 0.

In next line there is check:

return documentElement ? documentElement.nodeName !== "HTML" : false;

So it returns false anyway.

4

most probably: undefined what else?

2

It's a shorthand for:

var b; // defaults to "undefined"
if (a) b = a.ownerDocument.documentElement || a.documentElement;

It is checking for whether the DOM documentElement has been created yet in the DOM tree. (0).documentElement accesses a non-existant property which defaults to undefined. If the "documentElement" is undefined, it has not been created yet.

This might be easier to visualize:

a.ownerDocument.documentElement || // try this first
a.documentElement || // fallback
undefined; //documentElement has not been created yet

It is not just "a cute syntax" like another answer suggested. It is "manual minification" because, in a dynamically typed language like JavaScript, a minifier cannot determine that "a" and "a.ownerDocument" might be of the same type and will therefore do little more than whitespace removal.

Running my above code through the Closure Compiler yields:

var b;a&&(b=a.documentElement||a.ownerDocument.documentElement);

Meanwhile, the "manually minified" version you presented in your question run through a minifier produces:

var b=(a?a.ownerDocument||a:0).documentElement;

Results:

Without manual minification (my code) + Closure minifier: 64 characters
With manual minification (your original code): 54 characters
With manual minification (your original code) + Closure minifier: 47 characters
0

The ownerDocument property returns the owner of document of a html node, as a document object. the html document itself is ownerDocument of an element. if it is null, i guess (0).documentElement return the initial document when page contains several documents. ownerdocument can be used to create html elments inside multiple documents in same page accordingly

2
  • 2
    Just an FYI, 0 doesn't have a documentElement property.
    – gen_Eric
    Sep 11, 2013 at 13:43
  • but documentElement have
    – Voonic
    Sep 11, 2013 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.