line-breaksappendchildjsdom

How can I more efficiently appendChild different elements in Javascript?


I'm trying to make a program that requires text with line breaks and superscript elements. I'm trying to figure out how to use up less lines with making the text.

For instance, this is how 2 lines seperated by 2 line breaks are written in my code.

textblock.appendChild(document.createTextNode("this is the first line."))
textblock.appendChild(document.createElement("br"))
textblock.appendChild(document.createElement("br"))
textblock.appendChild(document.createTextNode("this is the second line."))

I'm wondering if I could somehow make this all one line.


Solution

  • Referencing the div element in which you want the text directly with ID (document.getElementById()), then with the innerHTML property to write html as string:

    document.getElementById("textblock").innerHTML = "This is the first line.<br><br>This is the second line.";
    

    *please, note that this will delete the current content of the element. (IDK if this will be a problem for you)