Why is .append (elem) being ignored?

  • 0
    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

  • 2 Answers
  • 0
    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

  • 0
    function render(message) {
    const p = document.createElement("p"); // создали p, его еще нигде нет в DOM, все ok
    p.textContent = message;
    windowChatUser1.append(p); // поместили наш p в windowChatUser1, с этого момента он есть в DOM
    windowChatUser2.append(p); // переместили наш p в windowChatUser2
    }
    it is logical that our p disappeared from windowChatUser1 when we moved to windowChatUser2, since one element cannot be in two parents at once

    Deep clone on second add: windowChatUser2.append (p.cloneNode (true));
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!