问题
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