Search code examples
jqueryhtmldomprependdetach

Detach element from DOM, insert it back in different spot


On a page, I need to detect all the entries that have an image in them, and add styles to the H1 and img, and p that contains the img in those entries. No problem so far.

  <div class="entry">
    <h1>Headline</h1>
    <p><img></p>
  </div>

  $("div.entry img").closest(".entry").find("h1").addClass("home-h1-adjust");
  $("div.entry img").closest("p").addClass("home-p-img-adjust");

To fully solve the problem I'm facing, I need to detach either the h1 or p, and reinsert to where the p comes before the h1, and this is for a series of entries, not all of which have an image.

I'm getting stuck on the proper way to loop through and prepend the detached elements in jQuery. Thanks.


Solution

  • Here was the solution that worked: iterate through all entries on the page, look for a image, attach the classes to the H1 and first p tag. Prepend the p containing the image above the H1, as the first child of the entry div.

      <div class="entry">
         <h1>Headline 1</h1>
         <p><img />Image? Yes</p>
         <p>Some Text that needs to stay put</p>
         <p>More copy text</p>
      </div>
    
      <div class="entry">
         <h1>Headline 2</h1>
         <p>Text in a non image entry</p>
         <p>This text has no image to keep it company</p>
      </div>
    
    
      $('div.entry').each(function(){
         var $this = $(this);
         if($this.find('img').length > 0) {
            $this.find('h1').addClass('home-h1-adjust');   
            var $img = $this.find('p').first().addClass('home-p-img-adjust');
            $this.prepend($img);
        }
      });
    

    http://jsfiddle.net/lockedown/vkeeD/1/