Simple jQuery, changing HTML

I think I’m half way there. I need to change this HTML with jQuery:


<div class="main-class">
  <div class="div1">
  content 1
  </div>
  <div class="div2">
  content 2
  </div>
</div>

$("div.main-class").each(function() {

  var holder = $(this);

  $("> div", holder).each(function(){

  //here I need to get entire div, including its contents, and place it before the main-class (and remove the old HTML)
  //holder.before() ???

}

Which should leave this:


<div class="div1">
content 1
</div>
<div class="div2">
content 2
</div>
<div class="main-class">
</div>

Hi there,

insertBefore() is your friend: http://api.jquery.com/insertBefore/

Here’s an example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Unbenanntes Dokument</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
  </head>

  <body>
    <div class="main-class">
      Main div
      <div class="div1">Div 1</div>
      <div class="div2">Div 2</div>
    </div>

    <script>
      $(document).ready(function() {
        $(".div1, .div2").insertBefore(".main-class");
      });
    </script>
  </body>
</html>

Great, thanks, but I actually need to do it using the code I posted, as there’s a lot more going on that I’ve stripped out.

My code needs to take out one at a time.

So I guess I need insertBefore, but I’m still not sure how that fits in with the code I posted:


$("div.main-class").each(function() {

  var holder = $(this);

  $("> div", holder).each(function(){

    //here I need to get entire div, including its contents, and place it before the main-class (and remove the old HTML)
    holder.insertBefore();

  }

}

Got it!

$(this).insertBefore($(this).parent());

As holder refers to <div class=“main-class”>, maybe this is better/easier to read:

$(this).insertBefore(holder);