Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

94
Visualizações
How to write if statement inside template literals

I want to write some logical if else statement inside the javascript template literals. I am adding html code through innerHTML and based on some logic, change html to something otherwise to something else. Please consider here that, this is an example code and the real code could be different or bigger

const main = document.getElementById('main');
const btn = document.getElementById('btn');

let x = 5;

btn.addEventListener('click', () => {
    main.innerHTML = `
    <h2>First</h2>
        ${if(x > 3) {
        return (
            `<h1>Its graeater also</h1>`
            )
    }}
  `;
})
<div id="main">
  
</div>

<button id="btn">
Click
</button>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You would do it using the Conditional (ternary) operator like so.

${x > 3 ? '<h1>It's greater than 3</h1>' : '<h1>It's less than 3</h1>'}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

about 4 years ago · Juan Pablo Isaza Relatório

0

You can either use ternary operator or && operator Like this :

       main.innerHTML = `
         <h2>First</h2> 
         ${x>3?'<h1>Its greater also</h1>':""}
      `;

or

main.innerHTML = `
        <h2>First</h2> 
        ${x>3&&'<h1>Its greater also</h1>'}
      `;

const main = document.getElementById('main');
const btn = document.getElementById('btn');

let x = 4;

btn.addEventListener('click', () => {
    //main.innerHTML = `
    //<h2>First</h2> 
    //${x>3?'<h1>Its greater also</h1>':""}
  //`;
   
    main.innerHTML = `
    <h2>First</h2> 
    ${x>3&&'<h1>Its greater also</h1>'}
  `;
})
<div id="main">
  
</div>

<button id="btn">
Click
</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda