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

How to display bold text in a <div> when content is added by JS?

The second element doesn’t display the expected result. Why and how to fix?

function process(sentence,element) {
    
    const words = sentence.split(' ');
    const container = document.getElementById(element);
    let index = 0;

    container.innerHTML = '';

    for (let i = 0; i < words.length; i++) {
        //console.log(words[i]);
        container.innerHTML += words[i] + ' '; // Display the word
    }
}

process("the quick <b>fox</b> jumps",'e1');   //displayed the word 'fox' as expected in bold
process("the quick <b> fox </b> jumps",'e2'); //displayed the word 'fox' as plain text, not as expected
div{
  border:1px solid #999;
  margin: 0 0 10px 0;
  display:block;
  font-size:22px
  }
<div id="e1"></div>
<div id="e2"></div>

>Solution :

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

In the second case, the text "fox" does not appear in bold because of the following:

There is a moment where you have added <b> to the innerHTML property, but not the closing </b>. This would be invalid HTML, and so the tag is immediately closed. Only in the next iteration of the loop the word "fox" is added, but it now comes after the <b></b> tags. And in the iteration after that, </b> is added to innerHTML, but it has no effect, as there is no matching <b>.

In conclusion, if you assign to innerHTML be aware that the HTML is validated and corrections will be applied to make it valid.

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