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

209
Visualizações
Seperate tag using multiple innerHTML in Javascript

Expected result is the second line should be bold:

it's regular
it's bold

I have this code and I want to separate the tag. The html output is : the "it's bold" is outside the . Is it possible to separate the html tag using multiple innerHTML?

var content = document.getElementById("content");
content.innerHTML += "it's regular";
content.innerHTML += "<br><b>";
content.innerHTML += "it's bold";
content.innerHTML += "</b>";
<div id="content"></div>   
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because you are writing straight to the innerHTML of the element, your browser is working overtime between the four lines (where you change the innerHTML) to make sure the HTML makes sense. In the second line, you add an un-closed <b>-tag, so the browser does whatever it can to make sure it makes sense after this change: It closes the tag. Now, when you later add text, and then add a closing tag - it doesn't make sense to close an already closed tag.

I recommend you use an intermediary variable here, it will allow you to do almost the exact same thing as before. Example below.

var content = document.getElementById("content");
let newHtml = ''
newHtml += "it's regular";
newHtml += "<br><b>";
newHtml += "it's bold";
newHtml += "</b>";
content.innerHTML = newHtml
<div id="content"></div>   

about 4 years ago · Juan Pablo Isaza Relatório

0

Why do you need to do that in multiple line? Simply you can do it in one line:

var content = document.getElementById("content");
content.innerHTML += "it's regular<br/><b>it's bold</b>";

But if you insist on to do that in multiple line, it is good idea to use a variable and after a valid html append it to your html:

var content = document.getElementById("content");
let firstlineHtml= "it's regular";
firstlineHtml += "<br><b>";
firstlineHtml += "it's bold";
firstlineHtml += "</b>";

content.innerHTML = firstlineHtml;
<div id="content"></div>   

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