Why is .append (elem) being ignored?
-
I find two divs with className = user1 and user2:
const windowChatUser1 = document.querySelector(".user1"), windowChatUser2 = document.querySelector(".user2");
And I try to add a P tag with the text to each:
function render(message) { const p = document.createElement("p"); p.textContent = message; windowChatUser1.append(p); windowChatUser2.append(p); }
In this case, only the "last" append is triggered and the previous one is ignored. Tell me why is this happening?JavaScript Anonymous, Aug 12, 2019 -
Not ignored.
A counter question - how can one element be in two places at once? No, no, you don't have to answer. Obviously, no way. To add the same elements in different places, make copies .Anonymous -
it is logical that our p disappeared from windowChatUser1 when we moved to windowChatUser2, since one element cannot be in two parents at oncefunction render(message) {
const p = document.createElement("p"); // создали p, его еще нигде нет в DOM, все ok
p.textContent = message;
windowChatUser1.append(p); // поместили наш p в windowChatUser1, с этого момента он есть в DOM
windowChatUser2.append(p); // переместили наш p в windowChatUser2
}
Deep clone on second add:windowChatUser2.append (p.cloneNode (true));
Anonymous
2 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!