I have this code:
if (window.content.document.getElementById("error-msg") != null )
{
if (window.content.document.getElementById("error-msg").offsetParent !== null)
{
...
}
}
Can it be written in one if statement?
I tried the following...
if ( (window.content.document.getElementById("error-msg") != null) || (window.content.document.getElementById("error-msg").offsetParent !== null) ) {}
But, it didn't work, and produces an error:
TypeError: window.content.document.getElementById(...) is null
I have this code:
if (window.content.document.getElementById("error-msg") != null )
{
if (window.content.document.getElementById("error-msg").offsetParent !== null)
{
...
}
}
Can it be written in one if statement?
I tried the following...
if ( (window.content.document.getElementById("error-msg") != null) || (window.content.document.getElementById("error-msg").offsetParent !== null) ) {}
But, it didn't work, and produces an error:
Share Improve this question edited Apr 21, 2015 at 2:01 user229044♦ 240k41 gold badges344 silver badges346 bronze badges asked Apr 21, 2015 at 1:58 whitesiroiwhitesiroi 2,8535 gold badges33 silver badges67 bronze badges 2TypeError: window.content.document.getElementById(...) is null
-
3
You need
&&
, not||
. – Amadan Commented Apr 21, 2015 at 2:00 - If only we had the existential operator! – Knu Commented Apr 21, 2015 at 2:08
2 Answers
Reset to default 8The mon idiom is to use the &&
operator like this
var errorMsg = window.content.document.getElementById("error-msg");
if (errorMsg && errorMsg.offsetParent) {
...
}
Here, JavaScript will evaluate errorMsg
first and if it is Truthy, then it will evaluate the errorMsg.offsetParent
part. The condition will be satisfied only if both the expressions in &&
are Truthy.
Note: The Truthy evaluation will return false
, if the expression being tested is 0
, false
etc (See the list of Falsy values here). So, if you want to test if they are not null
, just write that explicitly, like this
if (errorMsg !== null && errorMsg.offsetParent !== null) {
...
}
On the other hand, the ||
operator will evaluate the second operator only if the first expression is Falsy. In your case, if
(window.content.document.getElementById("error-msg") != null)
is true
, it means that getElementById("error-msg")
returns null
. Since the first expression is evaluated to be Truthy, it evaluates the other expression and it effectively tries to check
null.offsetParent !== null
That is why it fails.
Maybe you want to use &&
if (a != null && b != null) {
// Do something.
}