Teres Teres - 1 year ago 77
Javascript Question

Prevent an undefined into one line code

Using document command there are some times which is not exist. Instead of using controls like document contains or type of into one if statement is it possible to make the control into one line and if the command doesn't exist take an NA like this:

document.querySelector('div#name span.fn').textContent || "NA";

Answer Source

You could do something like this:

(document.querySelector('div#name span.fn') || {}).textContent || "NA";

If the querySelector call evaluates to null, it will return the object, which won't have a textContent, so it will return NA.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download