[英]How to append a div inside another div?
I'm pretty new to JS, and still learning.我对 JS 还很陌生,还在学习中。 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.我想在另一个内部添加带有类消息包装器的 a ,其中包含用户名、日期和消息。
// 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只是为了澄清我希望这个最终结果为 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);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.