Restructuring HTML using jQuery

jquery, xhtml

Solution

You should use wrapAll in your case since your wrapping multiple elements at once into the same element.

  <script type="text/javascript" charset="utf-8">
  $(document).ready(function(){  
    $('#restructure').toggle(
      function() {
        alert('removing structure');
        var module_list = $("#modules > div > div");
        $("#modules").html(module_list);
      },
      function() {
        alert('replacing structure');
        var next;
        while((next = $('#modules > div.column_left:first, #modules > div.column_right:first')).length)
        {
          next.wrapAll('<div class="two_column_box"></div>');
        }
      }
    );
  });
  </script>

Problem

I have some HTML that I need to toggle between two structures - one nested, and one un-nested - to make it easier for users to sort page components in a cms. Here's the before html... ``` <p><a href="#" id="restructure">Toggle Structure</a></p> <div id="modules"> <div class="two_column_box"> <div class="column_left"> <p>Some text</p> </div> <div class="column_right"> <p>Some text</p> </div> </div> <div class="two_column_box"> <div class="column_left"> <p>Some text</p> </div> <div class="column_right"> <p>Some text</p> </div> </div> </div> ``` and after html... ``` <p><a href="#" id="restructure">Toggle Structure</a></p> <div id="modules"> <div class="column_left"> <p>Some text</p> </div> <div class="column_right"> <p>Some text</p> </div> <div class="column_left"> <p>Some text</p> </div> <div class="column_right"> <p>Some text</p> </div> </div> ``` I can strip out the extra divs, no trouble, but putting them back afterwards - I just don't get how to build up html from plain text and existing DOM elements. Here's the code I have so far... ``` <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $('#restructure').toggle( function() { alert('removing structure'); var module_list = $("#modules > div > div"); $("#modules").html(module_list); }, function() { alert('replacing structure'); var idx = 1; var next; var structure = $(""); while((next = $('#modules > div:nth-child(' + idx++ + ')')).length) { var element = next.clone(); if(idx%2==1) { $(structure).append('<div class="two_column_box">').append(element); } else { $(structure).append(element).append('</div>'); } } $("#modules").html(structure); } ); }); </script> ``` Any help in getting the second function of the toggle to work (or in a more idiomatic version of the working code) would be much appreciated...

Original source