Short function to switch between innerHTML and textContent without full if else statement


This isn’t a problem, more of a curiosity. I have an anonymous arrow function that writes data to the screen.

const output = (message, selector, html=false) => {
  if (html) {
    selector.innerHTML += message;
  } else {
    selector.textContent += message;

Pretty straightforward and easy to implement and use. It isn’t too long, but I am curious if I can make a one line function; essentially collapsing the if the else statement into a ternary.

Something like this:

const output = (message, selector, html=false) => selector.(html?innerHTML:textContent) = message;

Again, my current function works flawlessly and this is more of a curiosity.

The above example has been tried and failed. Additionally I tried the following, which failed, as I knew it would.

const output = (message, selector, html=false) => selector.${(html?innerHTML:textContent)} = message;

>Solution :

I think you’re looking for this:

const output = (message, selector, html=false) => {
  selector[html ? 'innerHTML' : 'textContent'] += message;

Leave a ReplyCancel reply