What's the most concise way to set a variable to a getElementById's value or a default value if the element is not found?

Viewed 78

I tried

var test = document.getElementById("some_element").value || "defaultvalue";

But since it returns null, that doesn't seem to work.

The shortest I could come up with so far is

var test = "defaultvalue";
if(document.getElementById("some_element") !== null) test = document.getElementById("some_element").value;

or

var test = (document.getElementById("some_element") !== null)?document.getElementById("some_element").value:"defaultvalue";

However, is there an even more concise way to write this fallback?

4 Answers

You can use the new optional chaining operator in combination with ||:

var test = document.getElementById("some_element")?.value || "defaultvalue";
console.log(test);

This is pretty new syntax - like always, when writing scripts, to support older browsers, use Babel to transpile for production.

The new operators are nice, but if you need full browser compatibility and don't [want to] use a transpiler, this may be the alternative:

console.log( 
  (document.getElementById("nothing") || {value: null})
    .value ||"default" 
);
.as-console-wrapper { top: 0; max-height: 100% !important; }

Slightly shorter version without checking if it is null and using optional chaining

var valueexists = document.getElementById("some_element")?.innerText ?? "defaultvalue";
var valuenotthere = document.getElementById("some_")?.innerText ?? "defaultvalue";
console.log(valueexists);
console.log(valuenotthere);
<div id="some_element">value present</div>

Related