document.documentElement used in "in" statement
Question by Gautham Renganathan
I saw this piece of code in jQuery’s source. I am a novice in javascript and I would like to know how this works.
if ( "getBoundingClientRect" in document.documentElement ) {
// do something...
}
How is it different from
if(document.documentElement.getBoundingClientRect) {
// do something...
}
…?
Answer by T.J. Crowder
That’s an expression using the in
operator. The in
operator checks to see if the target object has a property with the given name (directly, or via the object’s prototype).
What it’s doing is seeing if document.documentElement
has a property with the name getBoundingClientRect
(which is a handy function jQuery would like to use if the browser provides it).
How is it different from
if(document.documentElement.getBoundingClientRect) { // do something... }
in
doesn’t require fetching the value of the property, just checking that it exists. Also note that the second form you list would test the truthiness of the value of the property. In the case of a function like getBoundingClientRect
that would be fine, but if you wanted to test something whose value might come back falsey (0
, ""
, etc.), it would fail even though the property exists.
You’ll see this sort of thing a lot when doing feature-detection. For instance, if you want to know if a browser supports the HTML5 placeholder
attribute:
if ('placeholder' in document.createElement('input')) {
// Yes, it does
}
This is an example where we couldn’t use the form if (document.createElement('input').placeholder)
because if the condition were false, we wouldn’t know whether it was false because the property didn’t exist, or false because the property existed but had a falsey value (and the default value for placeholder
is ""
, which is indeed falsey).
Answer by Starx
The in
operator checks to see if a given property is or present within a specified object or not. SO,
if ( "getBoundingClientRect" in document.documentElement ) {
// do something...
}
will check if getBoudingClientRect
property is available in document.documentElement
Object.
Moreover, you might want to read the article form John Resig himself, who has well explained, Why it is used.