0
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.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • 1
    Why not simply using `if`? You aren't using the return value of your ternary anyway... – CherryDT Oct 06 '21 at 06:19
  • I agreed but I want the code in minimum lines possible. –  Oct 07 '21 at 05:19
  • Then use a single-line `if`. But in general "minimum lines possible" is a bad idea, code needs to be readablenajd maintainable and that's usually a conflicting goal to "minimum lines possible". – CherryDT Oct 07 '21 at 05:31
  • One of the shortest ways would probably be `const clear_error = id => (document.getElementById(id) ?? {}).innerHTML = ''` but I think it's confusing to read... – CherryDT Oct 07 '21 at 05:35

2 Answers2

2

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 = "";
  }
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

Just use null :

(document.getElementById('jj') != undefined) ? (document.getElementById(id).innerHTML = "") : null
Toxy
  • 696
  • 5
  • 9