Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
Cómo escribir declaraciones if dentro de literales de plantilla

Quiero escribir una declaración lógica if else dentro de los literales de la plantilla de javascript. Estoy agregando código html a través de innerHTML y, según alguna lógica, cambio html a algo diferente a otra cosa. Tenga en cuenta aquí que este es un código de ejemplo y el código real podría ser diferente o más grande

 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 answers
Answer question

0

Lo haría usando el operador Condicional (ternario) así.

 ${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 Report

0

Puede usar el operador ternario o el operador && Así:

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

o

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!