HTML and CSS Reference
In-Depth Information
Detecting properties
For example, along with the document.body shortcut property,
in HTML5 we now have document.head . Not so exciting, but
still useful when you want to inject some script element, for
instance. As this is simply a property, it's easy to test for its
existence and to set it if it's not available:
if (document.getElementsByTagName('head')[0] !==
¬ document.head) {
document.head = document.getElementsByTagName('head')[0];
}
When simplified, it looks like this:
document.head || (document.head =
¬ document.getElementsByTagName('head')[0]);
In our code, we're testing for document.head , and if it has a
falsey value (in fact, undefined ), we explicitly set document.head
to the head element. However, rarely in the wastelands of cross-
browser support is anything that simple. The potential problem
with this code is that if you were to generate an iframe dynami-
cally in JavaScript, its document wouldn't have the head property
unless you ran this code against it. Not a big problem—we just
rerun the code—but it's worth bearing in mind (hat tip to Mathias
Bynens for the code, and Lea Verou for flagging iframes).
Another common detection method is to test for the existence
of a particular property in an HTML element. For example, to
test if the browser has native support for the details element,
we create the element and then test if the open property (which
we know is part of the standard details implementation) exists,
so we create this element on the fly, and test if said property
is present:
if (!'open' in document.createElement('details')) {
// does not have native support, let's polyfill it...
}
What we're asking here is: does the open property exist on the
details element. It doesn't have to be in the DOM to give us an
accurate reading of true or false.
NoTE A falsy value in
JavaScript is one that
returns false in a test though
doesn't particularly have to be
the value false. For example,
testing (in an if statement) the
value of an empty string, the
number 0 or the expression 1 - 1
all have falsy values.
 
 
Search WWH ::




Custom Search