title: An efficient way to change this DOM structure in jQuery
body: <p>i want to reform the structure of a certain element. currently, it roughly resembles this structure.</p>
  
  <pre><code>&lt;li&gt;
      &lt;a class="unitWrapper" href="location_url"&gt;
          stray textNode
          &lt;img src="project1.jpg"&gt;
      &lt;/a&gt;
      &lt;a class="unitWrapper" href="another_url"&gt;
          link text
      &lt;/a&gt;    
      &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt;                     
      &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt; 
  &lt;/li&gt;
  </code></pre>
  
  <p>and i want it to be built into the following structure using jQuery which in summary: </p>
  
  <ul>
  <li>gets the first link found in the list item</li>
  <li>unwrap it from it's contents</li>
  <li>use it to wrap everything in the list item</li>
  <li>if the link unwrapped contained text, wrap them in <code>&lt;p&gt;</code></li>
  </ul>
  
  <p>here's the new structure:</p>
  
  <pre><code>&lt;li&gt;
      &lt;a href="location_url"&gt;
          &lt;p&gt;stray textNode&lt;/p&gt;
          &lt;img src="project1.jpg"&gt;
          &lt;a class="unitWrapper" href="another_url"&gt;
              link text
          &lt;/a&gt;    
          &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt;                     
          &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit.&lt;/p&gt;
      &lt;/a&gt;
  &lt;/li&gt;
  </code></pre>
  
  <p>and the jQuery code that i have now (which is kinda clunky) is this:</p>
  
  <pre><code>$('li').find('.unitWrapper').eq(0).each(function() { //get only the first link
      var $link = $(this);
  
      var $wrapperLink = $('&lt;a/&gt;');                   //the wrapper link
      var $strayWrapper = $('&lt;p/&gt;');                  //wrapper for stray textNodes like "link text" above
  
      $wrapperLink.attr('href', $link.attr('href'));  //copy link's location to the wrapper
  
      $link.contents()                     //get all the link's contents
          .unwrap()                        //unwrap it
          .parent()                        //go to the parent (&lt;li&gt;)
          .contents()                      //get all li's contents
          .wrapAll($wrapperLink)           //wrap it with the &lt;a&gt; created earlier 
          .filter(function(){                         
              return this.nodeType == 3;   //get all stray text nodes
          })
          .wrapAll($strayWrapper);         //wrap them with the &lt;p&gt; created earlier
  });​
  </code></pre>
  
  <p>is there a better approach to doing this? and the only bearings i have is the <code>&lt;li&gt;</code> and the selector string <code>.unitWrapper</code></p>