简体   繁体   中英

How to append a div inside another div?

I'm pretty new to JS, and still learning. I'm trying to practice making some fun projects, but I simply just can't figure this one out.

I want to append a with the class message-wrapper, inside another , with the username, date and message inside.

// Output message to DOM
function outputMessage(message) {
    const div = document.createElement('div');
    div.classList.add('message-wrapper');
    const div2 = document.createElement('div');
    div.classList.add('message');

    if(message.username === username) {
        div.classList.add('me');
    }

    div.innerHTML = `<p class="meta">${message.username} <span>${message.time}</span></p>
    <p class="text">
        ${message.text}
    </p>`;
    document.querySelector('.chat-messages').appendChild(div);
};

Just to clarify I want this end result as HTML

<div class="message-wrapper">
   <div class="message me">
      <p class="meta">username <span>time</span></p>
      <p class="text">Lorem ipsum dolar sit amet</p>
   </div>
</div>

Corrected code below, see embedded comments.

function outputMessage(message) {
    const div = document.createElement('div');
    div.classList.add('message-wrapper');
    const div2 = document.createElement('div');
    div2.classList.add('message'); // make sure you add the class to the second div

    if(message.username === username) {
        div2.classList.add('me'); // same, add class to div2, not div
    }

    div2.innerHTML = `<p class="meta">${message.username} <span>${message.time}</span></p>
    <p class="text">
        ${message.text}
    </p>`; // make sure you are setting the inner HTML of the second div (div2), the one with classes "message", "me", not the outer div

    document.querySelector('.chat-messages').appendChild(div);
    // after appending the outer div to a node in the DOM, append the second div as a child of the "message-wrapper" div
    document.querySelector('.message-wrapper').appendChild(div2);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM