javascriptcreateelementcreatetextnode

Insert HTML in DOM


I need to insert this code JS in my html :

   var1 = "texte1" + "\ntext2"

I used:

var newPara = document.createElement('h1');
var texte = document.createTextNode(var1);
newPara.appendChild(texte);
document.body.appendChild(newPara);

When I alter this code, there is no problem. But I can't insert in HTML because var1 isn't TextNode. (I would like find a solutions without Jquery).


Solution

  • I am confused, so are you trying to insert just the text into the element you created? Or pure JavaScript code into the HTML? If just text, get the element by tag or id (id ideally, more direct way less room for error and element checking), then insert the text into the innerHTML

    document.GetElementById("IDValue").innerHTML = textValue
    

    UPDATE: As one of your responses said, set the innerHTML property before appending the element if it does not exist.