Eric Leslie
Eric Leslie

Reputation: 51

Make Portion of String Bold When Creating

I am creating <p> elements within a div dynamically, depending on how many items are in my codeArray. The amount could be different every time, so I can't just hard code the elements. This is the best way I have come up with so far:

  for(i=1;i<codeArray.length;i++){
    if(factArray[i] != 0){
      let para = document.createElement('p');
      let node = document.createTextNode(codeArray[i] + " = " + factArray[i]);
      para.appendChild(node);

      let element = document.getElementById('leftModal');
      element.appendChild(para);
    }
  }

My issue is that I would like the first part of the string (before the '=') to be bold, and the second half (factArray[i]) to be normal font weight. Is there a way I can do this?

Upvotes: 0

Views: 1244

Answers (1)

Heretic Monkey
Heretic Monkey

Reputation: 12115

Just put the text you want bold into an element you make bold. b elements are usually bold in browser's default stylesheets...

  for(i=1;i<codeArray.length;i++){
    if(factArray[i] != 0){
      let para = document.createElement('p');
      let bold = document.createElement('b');
      let boldNode = document.createTextNode(codeArray[i]);
      bold.appendChild(boldNode);
      para.appendChild(bold);
      let node = document.createTextNode(" = " + factArray[i]);
      para.appendChild(node);

      let element = document.getElementById('leftModal');
      element.appendChild(para);
    }
  }

Upvotes: 2

Related Questions