john frankit
john frankit

Reputation: 3

HTML tag to javascript createElement

I'm having a lot of problems trying to write an HTML code in Javascript DOM. This website is my last hope. I want to convert this HTML tag:

<div class="received_msg">
   <div class="received_withd_msg">
      <p>
         <b>Username: </b> Hello everyone!
      </p>
   </div>
</div>

This is what I have written so far:

var div2 = document.createElement('div');
div2.className = 'received_msg';

var div3 = document.createElement('div');
div3.className = 'received_withd_msg';

var par = document.createElement('p');

var bold = document.createElement('b')

div2.innerHTML += div3.outerHTML;
par.innerHTML += bold.innerHTML + data.username + ' : ' + data.msg;

document.querySelector('#message').append(div2);
document.querySelector('#message').append(par);

The above javascript code doesn't print out the HTML code that I want. What's the proper way to do it?

Note that data.username and data.msg are variables referenced in the full code.

Upvotes: 0

Views: 624

Answers (2)

Sidorina
Sidorina

Reputation: 66

Writing HTML using vanilla JS might be truly confusing :) As written above, appending children to parent elements would be easier and better in many ways. Just to complete the whole idea with your case and all the variables:

var data = {username: 'John Doe', msg: 'Hello World!'};
var root = document.querySelector('#root');

var div2 = document.createElement('div');
div2.className = 'received_msg';

var div3 = document.createElement('div');
div3.className = 'received_withd_msg';

var par = document.createElement('p');
var bold = document.createElement('b');
bold.textContent = `${data.username}: `;
par.appendChild(bold);
var text = document.createTextNode(data.msg);
par.appendChild(text);

div3.appendChild(par);
div2.appendChild(div3);
root.appendChild(div2);
<div id="root"></div>

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You should be appending the elements you create to their parent elements

var div2 = document.createElement('div');
div2.className = 'received_msg';

var div3 = document.createElement('div');
div3.className = 'received_withd_msg';

var par = document.createElement('p');

var bold = document.createElement('b');
bold.textContent = "hello";
// var boldTxt = document.createTextNode("Hello");
// bold.appendChild(boldTxt);


var txt = document.createTextNode(" World");

div2.appendChild(div3);
div3.appendChild(par);
par.appendChild(bold);
par.appendChild(txt);

document.body.append(div2);

Upvotes: 1

Related Questions