admin管理员组文章数量:1379117
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.
}
本文标签: How to skip the second part of (JavaScript if statement) if the first part is falseStack Overflow
版权声明:本文标题:How to skip the second part of (JavaScript if statement) if the first part is false - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744041812a2580794.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论