Home > Back-end >  how to write condition into innerHTML correctly?
how to write condition into innerHTML correctly?

Time:10-14

this code doesn't work:

el.innerHTML = {
  `<span>title</span>
    ${menuOpened &&
       `<div>
         <span>opened</span>
       </div>`
    }
  `
}

how write it correctly?

CodePudding user response:

I think you can't use a string template inside another ` inside string template. I might be wrong but I would work around it using other quotes.

el = {};
menuOpened = true
el.innerHTML =
  `<span>title</span>
    ${menuOpened && '<div><span>opened</span></div>' }
  `;
  
console.log(el)  

CodePudding user response:

Well, of course you can do it in one-liner template, but for readability of your code you can split it on multiple steps in classic way, check inline comments:

// Set your must have html
let html = `<span>title</span>`;

// Pre-set condition for example purpose
const menuOpened = true;

// Append html if condition is true
if(menuOpened) html  = `<div><span>opened</span></div>`;

// Then inner html
// For now we'll just console log it
console.log(html);

But in case you have more complex html and you need to insert data, not add it like in your case, then:

// Pre-set condition for example purpose
const menuOpened = true;

// Set code for menu
const menu = menuOpened ? `<div><span>opened</span></div>` : '';

// Set your html template
const html = `<div><span>title</span>${menu}</div>`;

// Then inner html
// For now we'll just console log it
console.log(html);

  • Related