Jonathan
Jonathan

Reputation: 2983

jQuery appendTo removes all DOM elements?

I'm trying to move child div elements between two different parent divs using jQuery .appendTo method but when the code is executed, the page turns blank and all elements have been removed from DOM. All that's left is pure text inside the tags. This is how the page is layed out (but of course not as simplistic as this example. For the actual site, see the below link):

 <div id="flip-container">
    <div id="flip-card">

      <div class="front face" id="frontPage">
      <div id="start"> text content...</div>
      <div id="about"> text content...</div>
      </div>


      <div class="back face" id="backPage">
      <div id="references"> text content... </div>
      <div id="contact"> text content... </div>
      </div>


    </div>
 </div>

I use jQuery to move the child divs between parent front/back face divs using the appendTo method:

 $("#references").appendTo($("#frontPage"));

This code alone works, this is just to give you an idea of how the actual site is laid out.

When the above code is executed, all divs are literally wiped away, leaving only the body tag and the div content. Hence, I cannot tell whether the div has actually been move correctly or not. This happens in all browsers and I've tried several different jQuery methods such as prependTo, append, inserAfter and clone. All with the same result. And yes, the specified divs do exist. Obviously, I've googled this frenetically but all I can find is this, which really doesn't answer the question: JQuery append element removes all html dom elements

So what is wrong here, what have I missed? Any help is greatly appreciated.

To the code in actual and where it fails, visist the below link. Click on one of the footer icons, then press the same again to see the problem appear.

http://utvecklingpunkten.se/list2LS/iscroll.html

Upvotes: 1

Views: 563

Answers (1)

Šime Vidas
Šime Vidas

Reputation: 185913

Look at your source code:

<div id="statisticsDiv" class="innerPages">
  <script> for(i=0;i<50;i++) {document.write("statistics "+i+"<br>"); }</script>
</div>

You are using document.write to create the content of the elements of your page.

Now, when you click on the "Statistics" icon (the second time), the DIV is relocated to a different part of the page. This causes the SCRIPT block to execute again. Live example Therefore, document.write will execute. As a result, the page will be destroyed.

The rule is that when document.write is executed after the page-load event, the page is destroyed and replaced with the new content provided to document.write.

My recommendation would be to avoid document.write. Instead, generate the content in the DOM-ready event-handler, and use jQuery to find the elements of your page and set their content.

Upvotes: 2

Related Questions