0

I want to create a paragraph element and add content to it. Basically i want to let the textContent of a paragraph element be a string.

What i have tried doing is:

var st="Hello";
con=document.getElementById("content");
var pv=document.createElement("p");
con.appendchild(pv);
pv.setAttribute("",st);
<span id="content"> </span>

What attribute should i use to add in the setAttribute function here? I tried using textContent but it's not an attribute. Any other way i can do this?

1
  • User pv.innerHTML = st; isntead of setAttribute. Commented Nov 18, 2019 at 9:32

3 Answers 3

4

You could do with elem.innerText instead of setAttribute

var st = "Hello";
var con = document.getElementById("content");
var pv = document.createElement("p");
con.appendChild(pv);
pv.innerText= st;
<span id="content"> </span>

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

Comments

0

You should use innerText to do this.

pv.innerText = "hello"

You can set and get the text value of an element using innerText.

More info on innerText can be found here: https://www.w3schools.com/jsref/prop_node_innertext.asp

Comments

0

You can also use innerHTML which can change not just the text but also the HTML.

let con_txt = document.getElementById("content_text");
let pv_txt = document.createElement("p");
con_txt.appendChild(pv_txt);
pv_txt.innerText = "From innerText";

let con_html = document.getElementById("content_html");
let pv_html = document.createElement("p");
con_html.appendChild(pv_html);
pv_html.innerHTML = "<b>innerHTML also works!</b>"; //You can use HTML tags here
<span id="content_text"></span>
<span id="content_html"></span>

Above result in HTML

<span id="content_text">
    <p>From innerText</p>
</span>
<span id="content_html">
    <p><b>innerHTML also works!</b></p>
</span>

More info about innerHTML

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.