1

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>

2
  • 1
    I edited your snippet and fixed the console errors var str3 = "<b>Description: </b" > ; is invalid Commented Jun 14, 2020 at 8:51
  • 1
    What do you want to style ? the created p tag ? Commented Jun 14, 2020 at 8:53

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to use js for styling, this would be it:

var catalogArray = [{
    desc: "Desc 1"
}]

var pos = 0;

const detailsDiv = document.getElementById("details");
var articleDecs = document.createElement("p");
articleDecs.setAttribute("class", "productDesc");
articleDecs.innerHTML = "Description:" + catalogArray[pos].desc;
articleDecs.style.fontWeight = "bold";
detailsDiv.appendChild(articleDecs);
<div id="details"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.