Search code examples
javascripthtmlcssinnerhtml

Is it possible to style some part of text in innerHtmlin JavaScript?


I want to style some part of my paragraph before appending it to html page. I have tried some methods but they are not working. see commented syntax. I want to style the word Description What is the proper way of doing this? Thank You.

const detailsDiv = document.getElementById("details");
var articleDecs = document.createElement("p");
articleDecs.setAttribute("class", "productDesc");
var str = "Description:  ";
//var str2 = str.bold();
//var str3 = "<b>Description:  </b>" ;
articleDecs.innerText = "Description: " +catalogArray[pos].desc;

//articleDecs.innerText = str2  +catalogArray[pos].desc;
//articleDecs.innerText = str3 "+catalogArray[pos].desc;
console.log(articleDecs);
detailsDiv.appendChild(articleDecs);
<div id="details"></div>


Solution

  • If you concatenate correctly and use innerHTML it works

    const catalogArray = [{
      desc: "Desc 1"
    }]
    
    let pos = 0
    
    const detailsDiv = document.getElementById("details");
    var articleDecs = document.createElement("p");
    articleDecs.setAttribute("class", "productDesc");
    var str1 = "Description:  ".bold();
    articleDecs.innerHTML = str1 + catalogArray[pos].desc;
    console.log(articleDecs);
    detailsDiv.appendChild(articleDecs);
    <div id="details"></div>

    But why not use CSS instead of .bold()

    const catalogArray = [{
      desc: "Desc 1"
    }]
    
    let pos = 0
    
    const detailsDiv = document.getElementById("details");
    var articleDecs = document.createElement("span");
    articleDecs.setAttribute("class", "productDesc");
    articleDecs.innerText = "Description:  ";
    detailsDiv.appendChild(articleDecs);
    detailsDiv.appendChild(document.createTextNode(catalogArray[pos].desc));
    .productDesc { font-weight:bold }
    <div id="details"></div>