Teres Teres - 5 months ago 41
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";


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.