How do I update the reference to an HTML element after I used appendChild with native javascriptHow to validate an email address in JavaScript?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I check if an array includes an object in JavaScript?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?

How to bake one texture for one mesh with multiple textures blender 2.8

The IT department bottlenecks progress. How should I handle this?

What prevents the use of a multi-segment ILS for non-straight approaches?

When were female captains banned from Starfleet?

How should I respond when I lied about my education and the company finds out through background check?

Redundant comparison & "if" before assignment

Count the occurrence of each unique word in the file

Is it possible to put a rectangle as background in the author section?

Electoral considerations aside, what are potential benefits, for the US, of policy changes proposed by the tweet recognizing Golan annexation?

Should I outline or discovery write my stories?

How do I color the graph in datavisualization?

Melting point of aspirin, contradicting sources

Problem with TransformedDistribution

Is it improper etiquette to ask your opponent what his/her rating is before the game?

What does "Scientists rise up against statistical significance" mean? (Comment in Nature)

Pre-mixing cryogenic fuels and using only one fuel tank

Biological Blimps: Propulsion

Is there any references on the tensor product of presentable (1-)categories?

How much character growth crosses the line into breaking the character

Is it better practice to read straight from sheet music rather than memorize it?

Why should universal income be universal?

Why can Carol Danvers change her suit colours in the first place?

Why did the EU agree to delay the Brexit deadline?

Why did the Mercure fail?



How do I update the reference to an HTML element after I used appendChild with native javascript


How to validate an email address in JavaScript?How do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do you get a timestamp in JavaScript?How do I check if an array includes an object in JavaScript?How do I include a JavaScript file in another JavaScript file?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How do I remove a particular element from an array in JavaScript?













2















I'm using native javascript to append an element to my DOM, which disappears after X seconds.



To append the element I create a document fragment with a function createHTML I then append this element to my container element.



var elementHTML = '<div>Test element appended</div>';
elementHTML = createHTML(elementHTML);
document.getElementById('append-container').appendChild(elementHTML);


I then set a timeout that removes the element from the DOM after x seconds



setTimeout(function() 
elementHTML.parentNode.removeChild(elementHTML);
, 2000, elementHTML);


Now this won't work because when you use appendChild, the elements get moved and the reference to the element is lost. I'm looking for a way to update the reference for elementHTML to the element I just appended to the DOM.



Basically I'm looking for the jQuery reference funcionality without using jQuery.



I could use a randomly generated ID to target the element or add a class and loop trough all the elements with that class and target the last one, but these methods feel ugly.



I'm wondering if there is some sort of callback when you append something to the DOM to target what you just appended or if my logic in going about this is just plain wrong.



FIDDLE










share|improve this question


























    2















    I'm using native javascript to append an element to my DOM, which disappears after X seconds.



    To append the element I create a document fragment with a function createHTML I then append this element to my container element.



    var elementHTML = '<div>Test element appended</div>';
    elementHTML = createHTML(elementHTML);
    document.getElementById('append-container').appendChild(elementHTML);


    I then set a timeout that removes the element from the DOM after x seconds



    setTimeout(function() 
    elementHTML.parentNode.removeChild(elementHTML);
    , 2000, elementHTML);


    Now this won't work because when you use appendChild, the elements get moved and the reference to the element is lost. I'm looking for a way to update the reference for elementHTML to the element I just appended to the DOM.



    Basically I'm looking for the jQuery reference funcionality without using jQuery.



    I could use a randomly generated ID to target the element or add a class and loop trough all the elements with that class and target the last one, but these methods feel ugly.



    I'm wondering if there is some sort of callback when you append something to the DOM to target what you just appended or if my logic in going about this is just plain wrong.



    FIDDLE










    share|improve this question
























      2












      2








      2








      I'm using native javascript to append an element to my DOM, which disappears after X seconds.



      To append the element I create a document fragment with a function createHTML I then append this element to my container element.



      var elementHTML = '<div>Test element appended</div>';
      elementHTML = createHTML(elementHTML);
      document.getElementById('append-container').appendChild(elementHTML);


      I then set a timeout that removes the element from the DOM after x seconds



      setTimeout(function() 
      elementHTML.parentNode.removeChild(elementHTML);
      , 2000, elementHTML);


      Now this won't work because when you use appendChild, the elements get moved and the reference to the element is lost. I'm looking for a way to update the reference for elementHTML to the element I just appended to the DOM.



      Basically I'm looking for the jQuery reference funcionality without using jQuery.



      I could use a randomly generated ID to target the element or add a class and loop trough all the elements with that class and target the last one, but these methods feel ugly.



      I'm wondering if there is some sort of callback when you append something to the DOM to target what you just appended or if my logic in going about this is just plain wrong.



      FIDDLE










      share|improve this question














      I'm using native javascript to append an element to my DOM, which disappears after X seconds.



      To append the element I create a document fragment with a function createHTML I then append this element to my container element.



      var elementHTML = '<div>Test element appended</div>';
      elementHTML = createHTML(elementHTML);
      document.getElementById('append-container').appendChild(elementHTML);


      I then set a timeout that removes the element from the DOM after x seconds



      setTimeout(function() 
      elementHTML.parentNode.removeChild(elementHTML);
      , 2000, elementHTML);


      Now this won't work because when you use appendChild, the elements get moved and the reference to the element is lost. I'm looking for a way to update the reference for elementHTML to the element I just appended to the DOM.



      Basically I'm looking for the jQuery reference funcionality without using jQuery.



      I could use a randomly generated ID to target the element or add a class and loop trough all the elements with that class and target the last one, but these methods feel ugly.



      I'm wondering if there is some sort of callback when you append something to the DOM to target what you just appended or if my logic in going about this is just plain wrong.



      FIDDLE







      javascript appendchild






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 7 at 7:40









      timotimo

      1,5371629




      1,5371629






















          2 Answers
          2






          active

          oldest

          votes


















          2














          The issue is that a DocumentFragment will move the contents of the fragment into the new place in the DOM, but the fragment itself will remain a fragment, not directly attached to anything:



          https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild




          If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.




          After all, otherwise, if the HTML string is



          <div>Test element appended</div><div>Test element 2 appended</div>


          what could the appended documentFragment refer to? It's couldn't be just one or the other <div>, nor could it be the parent element (which was already in the DOM, and was not created with the fragment).



          So, once a documentFragment is appended, it cannot be removed all in one go.



          If the fragment is guaranteed to contain only one element, like in your example, then select that one element and append it instead (and then you can properly reference its parentNode).






          // though using a documentFragment in the first place is a bit odd
          // if you're not going to append it

          var createHTML = function(htmlStr)
          var frag = document.createDocumentFragment(),
          temp = document.createElement('div');
          temp.innerHTML = htmlStr;
          while (temp.firstChild)
          frag.appendChild(temp.firstChild);

          return frag;


          var appendItems = function()
          const elementHTML = '<div>Test element appended</div>';
          const fragment = createHTML(elementHTML);
          const fragmentElm = fragment.children[0];
          document.getElementById('append-container').appendChild(fragmentElm);
          setTimeout(function()
          fragmentElm.parentNode.removeChild(fragmentElm);
          , 2000, elementHTML);


          document.getElementById('test-append').addEventListener('click', appendItems);

          <div id="append-container">

          </div>

          <button id="test-append">
          Test
          </button>





          Another option is to iterate through all appended nodes and .remove() them:






          var createHTML = function(htmlStr) 
          var frag = document.createDocumentFragment(),
          temp = document.createElement('div');
          temp.innerHTML = htmlStr;
          while (temp.firstChild)
          frag.appendChild(temp.firstChild);

          return frag;


          var appendItems = function()
          const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
          const fragment = createHTML(elementHTML);
          const fragmentElms = [...fragment.children];
          const container = document.getElementById('append-container');
          fragmentElms.forEach((elm) =>
          container.appendChild(elm);
          );
          setTimeout(function()
          fragmentElms.forEach((elm) =>
          elm.remove();
          );
          , 2000, elementHTML);


          document.getElementById('test-append').addEventListener('click', appendItems);

          <div id="append-container">

          </div>

          <button id="test-append">
          Test
          </button>








          share|improve this answer

























          • I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

            – timo
            Mar 7 at 8:15











          • If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

            – CertainPerformance
            Mar 7 at 8:16











          • I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

            – timo
            Mar 7 at 8:49











          • Turns out I just needed to replace getElementById with querySelector

            – timo
            Mar 7 at 9:02


















          1














          Appending the nodes in the while loop is unnecessary: innerHTML already does that for you.



          var createHTML = function(htmlStr) 
          var temp = document.createElement('div');
          temp.innerHTML = htmlStr;
          return temp;



          In this way – without the DOM fragment – removing the element after the timeout works as expected.






          share|improve this answer






















            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55038461%2fhow-do-i-update-the-reference-to-an-html-element-after-i-used-appendchild-with-n%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            The issue is that a DocumentFragment will move the contents of the fragment into the new place in the DOM, but the fragment itself will remain a fragment, not directly attached to anything:



            https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild




            If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.




            After all, otherwise, if the HTML string is



            <div>Test element appended</div><div>Test element 2 appended</div>


            what could the appended documentFragment refer to? It's couldn't be just one or the other <div>, nor could it be the parent element (which was already in the DOM, and was not created with the fragment).



            So, once a documentFragment is appended, it cannot be removed all in one go.



            If the fragment is guaranteed to contain only one element, like in your example, then select that one element and append it instead (and then you can properly reference its parentNode).






            // though using a documentFragment in the first place is a bit odd
            // if you're not going to append it

            var createHTML = function(htmlStr)
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElm = fragment.children[0];
            document.getElementById('append-container').appendChild(fragmentElm);
            setTimeout(function()
            fragmentElm.parentNode.removeChild(fragmentElm);
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            Another option is to iterate through all appended nodes and .remove() them:






            var createHTML = function(htmlStr) 
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElms = [...fragment.children];
            const container = document.getElementById('append-container');
            fragmentElms.forEach((elm) =>
            container.appendChild(elm);
            );
            setTimeout(function()
            fragmentElms.forEach((elm) =>
            elm.remove();
            );
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>








            share|improve this answer

























            • I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

              – timo
              Mar 7 at 8:15











            • If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

              – CertainPerformance
              Mar 7 at 8:16











            • I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

              – timo
              Mar 7 at 8:49











            • Turns out I just needed to replace getElementById with querySelector

              – timo
              Mar 7 at 9:02















            2














            The issue is that a DocumentFragment will move the contents of the fragment into the new place in the DOM, but the fragment itself will remain a fragment, not directly attached to anything:



            https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild




            If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.




            After all, otherwise, if the HTML string is



            <div>Test element appended</div><div>Test element 2 appended</div>


            what could the appended documentFragment refer to? It's couldn't be just one or the other <div>, nor could it be the parent element (which was already in the DOM, and was not created with the fragment).



            So, once a documentFragment is appended, it cannot be removed all in one go.



            If the fragment is guaranteed to contain only one element, like in your example, then select that one element and append it instead (and then you can properly reference its parentNode).






            // though using a documentFragment in the first place is a bit odd
            // if you're not going to append it

            var createHTML = function(htmlStr)
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElm = fragment.children[0];
            document.getElementById('append-container').appendChild(fragmentElm);
            setTimeout(function()
            fragmentElm.parentNode.removeChild(fragmentElm);
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            Another option is to iterate through all appended nodes and .remove() them:






            var createHTML = function(htmlStr) 
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElms = [...fragment.children];
            const container = document.getElementById('append-container');
            fragmentElms.forEach((elm) =>
            container.appendChild(elm);
            );
            setTimeout(function()
            fragmentElms.forEach((elm) =>
            elm.remove();
            );
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>








            share|improve this answer

























            • I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

              – timo
              Mar 7 at 8:15











            • If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

              – CertainPerformance
              Mar 7 at 8:16











            • I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

              – timo
              Mar 7 at 8:49











            • Turns out I just needed to replace getElementById with querySelector

              – timo
              Mar 7 at 9:02













            2












            2








            2







            The issue is that a DocumentFragment will move the contents of the fragment into the new place in the DOM, but the fragment itself will remain a fragment, not directly attached to anything:



            https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild




            If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.




            After all, otherwise, if the HTML string is



            <div>Test element appended</div><div>Test element 2 appended</div>


            what could the appended documentFragment refer to? It's couldn't be just one or the other <div>, nor could it be the parent element (which was already in the DOM, and was not created with the fragment).



            So, once a documentFragment is appended, it cannot be removed all in one go.



            If the fragment is guaranteed to contain only one element, like in your example, then select that one element and append it instead (and then you can properly reference its parentNode).






            // though using a documentFragment in the first place is a bit odd
            // if you're not going to append it

            var createHTML = function(htmlStr)
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElm = fragment.children[0];
            document.getElementById('append-container').appendChild(fragmentElm);
            setTimeout(function()
            fragmentElm.parentNode.removeChild(fragmentElm);
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            Another option is to iterate through all appended nodes and .remove() them:






            var createHTML = function(htmlStr) 
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElms = [...fragment.children];
            const container = document.getElementById('append-container');
            fragmentElms.forEach((elm) =>
            container.appendChild(elm);
            );
            setTimeout(function()
            fragmentElms.forEach((elm) =>
            elm.remove();
            );
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>








            share|improve this answer















            The issue is that a DocumentFragment will move the contents of the fragment into the new place in the DOM, but the fragment itself will remain a fragment, not directly attached to anything:



            https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild




            If the given child is a DocumentFragment, the entire contents of the DocumentFragment are moved into the child list of the specified parent node.




            After all, otherwise, if the HTML string is



            <div>Test element appended</div><div>Test element 2 appended</div>


            what could the appended documentFragment refer to? It's couldn't be just one or the other <div>, nor could it be the parent element (which was already in the DOM, and was not created with the fragment).



            So, once a documentFragment is appended, it cannot be removed all in one go.



            If the fragment is guaranteed to contain only one element, like in your example, then select that one element and append it instead (and then you can properly reference its parentNode).






            // though using a documentFragment in the first place is a bit odd
            // if you're not going to append it

            var createHTML = function(htmlStr)
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElm = fragment.children[0];
            document.getElementById('append-container').appendChild(fragmentElm);
            setTimeout(function()
            fragmentElm.parentNode.removeChild(fragmentElm);
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            Another option is to iterate through all appended nodes and .remove() them:






            var createHTML = function(htmlStr) 
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElms = [...fragment.children];
            const container = document.getElementById('append-container');
            fragmentElms.forEach((elm) =>
            container.appendChild(elm);
            );
            setTimeout(function()
            fragmentElms.forEach((elm) =>
            elm.remove();
            );
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>








            // though using a documentFragment in the first place is a bit odd
            // if you're not going to append it

            var createHTML = function(htmlStr)
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElm = fragment.children[0];
            document.getElementById('append-container').appendChild(fragmentElm);
            setTimeout(function()
            fragmentElm.parentNode.removeChild(fragmentElm);
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            // though using a documentFragment in the first place is a bit odd
            // if you're not going to append it

            var createHTML = function(htmlStr)
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElm = fragment.children[0];
            document.getElementById('append-container').appendChild(fragmentElm);
            setTimeout(function()
            fragmentElm.parentNode.removeChild(fragmentElm);
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            var createHTML = function(htmlStr) 
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElms = [...fragment.children];
            const container = document.getElementById('append-container');
            fragmentElms.forEach((elm) =>
            container.appendChild(elm);
            );
            setTimeout(function()
            fragmentElms.forEach((elm) =>
            elm.remove();
            );
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>





            var createHTML = function(htmlStr) 
            var frag = document.createDocumentFragment(),
            temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            while (temp.firstChild)
            frag.appendChild(temp.firstChild);

            return frag;


            var appendItems = function()
            const elementHTML = '<div>Test element appended</div><div>Test element 2 appended</div>';
            const fragment = createHTML(elementHTML);
            const fragmentElms = [...fragment.children];
            const container = document.getElementById('append-container');
            fragmentElms.forEach((elm) =>
            container.appendChild(elm);
            );
            setTimeout(function()
            fragmentElms.forEach((elm) =>
            elm.remove();
            );
            , 2000, elementHTML);


            document.getElementById('test-append').addEventListener('click', appendItems);

            <div id="append-container">

            </div>

            <button id="test-append">
            Test
            </button>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 7 at 8:05

























            answered Mar 7 at 7:50









            CertainPerformanceCertainPerformance

            95.1k165685




            95.1k165685












            • I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

              – timo
              Mar 7 at 8:15











            • If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

              – CertainPerformance
              Mar 7 at 8:16











            • I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

              – timo
              Mar 7 at 8:49











            • Turns out I just needed to replace getElementById with querySelector

              – timo
              Mar 7 at 9:02

















            • I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

              – timo
              Mar 7 at 8:15











            • If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

              – CertainPerformance
              Mar 7 at 8:16











            • I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

              – timo
              Mar 7 at 8:49











            • Turns out I just needed to replace getElementById with querySelector

              – timo
              Mar 7 at 9:02
















            I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

            – timo
            Mar 7 at 8:15





            I wasn't even aware I could add multiple siblings via this method. In my usecase, there will always be a single parent element, so I'm going with your first option.

            – timo
            Mar 7 at 8:15













            If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

            – CertainPerformance
            Mar 7 at 8:16





            If there's guaranteed to be a single parent, then you can ditch the fragment entirely and simply return temp's firstChild

            – CertainPerformance
            Mar 7 at 8:16













            I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

            – timo
            Mar 7 at 8:49





            I was using the fragment because I want to add an eventlistener to part of the added element. I thought this was not possible without fragment. I now found the issue lay in the fact that I was targeting a part of the dynamic element with document.getElementById while it was not yet added to the DOM. This was why is WAS working with fragment. This is a different issue which I need to inspect further before asking follow up questions. Your provided sollution is still valid for the question as is, hence I will keep it accepted.

            – timo
            Mar 7 at 8:49













            Turns out I just needed to replace getElementById with querySelector

            – timo
            Mar 7 at 9:02





            Turns out I just needed to replace getElementById with querySelector

            – timo
            Mar 7 at 9:02













            1














            Appending the nodes in the while loop is unnecessary: innerHTML already does that for you.



            var createHTML = function(htmlStr) 
            var temp = document.createElement('div');
            temp.innerHTML = htmlStr;
            return temp;



            In this way – without the DOM fragment – removing the element after the timeout works as expected.






            share|improve this answer



























              1














              Appending the nodes in the while loop is unnecessary: innerHTML already does that for you.



              var createHTML = function(htmlStr) 
              var temp = document.createElement('div');
              temp.innerHTML = htmlStr;
              return temp;



              In this way – without the DOM fragment – removing the element after the timeout works as expected.






              share|improve this answer

























                1












                1








                1







                Appending the nodes in the while loop is unnecessary: innerHTML already does that for you.



                var createHTML = function(htmlStr) 
                var temp = document.createElement('div');
                temp.innerHTML = htmlStr;
                return temp;



                In this way – without the DOM fragment – removing the element after the timeout works as expected.






                share|improve this answer













                Appending the nodes in the while loop is unnecessary: innerHTML already does that for you.



                var createHTML = function(htmlStr) 
                var temp = document.createElement('div');
                temp.innerHTML = htmlStr;
                return temp;



                In this way – without the DOM fragment – removing the element after the timeout works as expected.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 7 at 8:10









                JoeJoe

                6151020




                6151020



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55038461%2fhow-do-i-update-the-reference-to-an-html-element-after-i-used-appendchild-with-n%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved