Home > Back-end >  I don't want the else part in tertiary operator
I don't want the else part in tertiary operator

Time:10-06

function clear_error(id){
    (document.getElementById(id) != undefined) ? (document.getElementById(id).innerHTML = "") : console.log('span is not created yet');
}

I have to check that a span element has been created/defined for my error or not, if it is created then remove the inner text for the new error if not then do nothing, as i have made an error function of it in the specified class.

CodePudding user response:

A ternary isn't the best tool here. Typically the conditional operator (? :) is used when you want to evaluate a condition and obtain a new value based on whether the condition is true/false. You can could && to short-circuit:

function clear_error(id) {
  const elem = document.getElementById(id); // store the element to avoid re-querying the DOM
  elem && elem.innerHTML = "";
}

but that to me doesn't read very well, so a standard if-statement would work better in my opinion:

function clear_error(id){
  const elem = document.getElementById(id); // store the element to avoid re-querying the DOM
  if(elem) {
    elem.innerHTML = "";
  }
}

CodePudding user response:

Just use null :

(document.getElementById('jj') != undefined) ? (document.getElementById(id).innerHTML = "") : null
  • Related