Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading