How to wrap multiple instances of selected elements into new <div>'s

╄→гoц情女王★ 提交于 2019-12-11 08:12:38

问题


I need to wrap the div's with the classes .left and .right into a new div. Having problems making this work as I need it to.

This is the original markup:

<div class="content-main">
  <div class="summary" id="listing_summary_3547">
    <div class="share"></div>
    <div class="left"></div>
    <div class="right"></div>
  </div>
  <div class="summary" id="listing_summary_12739">
    <div class="share"></div>
    <div class="left"></div>
    <div class="right"></div>
  </div>        
  <div class="summary" id="listing_summary_4">
    <div class="share"></div>
    <div class="left"></div>
    <div class="right"></div>
  </div>
</div>

This is the result I need:

<div class="content-main">
   <div class="summary" id="listing_summary_3547">
      <div class="share"></div>
      <div class="summary-inside">
         <div class="left"></div>
         <div class="right"></div>
      </div>
   </div>
   <div class="summary" id="listing_summary_12739">
      <div class="share"></div>
      <div class="summary-inside">
         <div class="left"></div>
         <div class="right"></div>
      </div>
   </div>
   <div class="summary" id="listing_summary_4">
      <div class="share"></div>
      <div class="summary-inside">
         <div class="left"></div>
         <div class="right"></div>
      </div>
   </div>
</div>

The script tag needs to reside within in the tags (no access to section). jQuery version is 1.3.2

The closest I am able to get on my own is:

    $('.summary .left,.summary .right').wrapAll('<div class="summary-inside"></div>')

However the result is wrong, the elements get all put together instead of being distributed the way I need them to be.


回答1:


This is now tested, and does, indeed, work:

$('.content-main .summary').each(
    function(){
        $(this).find('.left,.right').wrapAll('<div class="summary-inside"></div>');
    });

JS Fiddle demo.

The text in the linked demo showing the html that you want is the updated html of the .content-main element, after manipulation with jQuery 1.3.2.



来源:https://stackoverflow.com/questions/8371209/how-to-wrap-multiple-instances-of-selected-elements-into-new-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!