最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to skip the second part of (JavaScript if statement) if the first part is false - Stack Overflow

programmeradmin0浏览0评论

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:

TypeError: window.content.document.getElementById(...) is null

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 2
  • 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
Add a ment  | 

2 Answers 2

Reset to default 8

The 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.
}
发布评论

评论列表(0)

  1. 暂无评论