I’m working on an application that’s printing out some text to the user in HTML with DOM. Below you can see my code and I have some questions regarding it.
-
Is there another way to create the text below with DOM (without using
innerHTML) that needs less code? -
What is the best way of making the text bold, eg. “Firstname” (just the text, not the content in the variable)?
Here is my JS:
header.appendChild(headertext);
p.appendChild(header);
var p2 = document.createElement('p');
var br = document.createElement('br');
var text1 = document.createTextNode("Firstname: " + firstname);
p2.appendChild(text1);
p2.appendChild(br);
var br2 = document.createElement('br');
var text2 = document.createTextNode("Lastname: " + lastname);
p2.appendChild(text2);
p2.appendChild(br2);
var br3 = document.createElement('br');
var text3 = document.createTextNode("Zip code: " + zipcode);
p2.appendChild(text3);
p2.appendChild(br3);
var br = document.createElement('br');
var text4 = document.createTextNode("Phone nr: " + phonenr);
p2.appendChild(text4);
p2.appendChild(br);
square.appendChild(p);
square.appendChild(p2);
I would refactor this
into a helper function:
And then:
To answer your second question, to make this text bold, I would create the content like the below
(I know you mentioned not using innerHTML, but I interpreted that as not wanting to use innerHTML in order to dump large, pre-formed html chunks in)