2011-10-14 50 views
1

就像标题所说的那样,我需要在div内包装一些div。这是HTML。使用jQuery将div封入到wrapper div

<div class="something1 message"> 
<span class="message-text">This is notification 1</span> 
<input type="text" /> 
</div> 

<div class="something2 message"> 
<span class="message-text">There can be multiple texts like this</span> 
<span class="message-text">There can be multiple texts like this</span> 
<span class="message-text">There can be multiple texts like this</span> 
<input type="text" /> 
</div> 

<div id="content-wrapper" class"message"> 
<span class="message-text">Anotherexample</span> 
<span class="message-text">There can be multiple texts like this</span> 
<input type="text" /> 
</div> 

现在我想什么,输出是:

<div class="something1 message"> 
<div class="message-text-wrapper"> 
    <span class="message-text">This is notification 1</span> 
</div> 
    <input type="text" /> 
    </div> 

    <div class="something2 message"> 
<div class="message-text-wrapper"> 
    <span class="message-text">There can be multiple texts like this</span> 
    <span class="message-text">There can be multiple texts like this</span> 
    <span class="message-text">There can be multiple texts like this</span> 
</div> 
    <input type="text" /> 
    </div> 

    <div id="content-wrapper" class"message"> 
<div class="message-text-wrapper"> 
    <span class="message-text">Anotherexample</span> 
    <span class="message-text">There can be multiple texts like this</span> 
</div> 
    <input type="text" /> 
    </div> 

基本上所有的“消息文本”跨度是invidual消息div中会我们包裹在里面消息文本wrappe DIV。

希望你明白。

+0

你打算把'单跨度'还是'多跨度',看起来你们都混在一起了。 – Deeptechtons

回答

1

这是行得通吗?这是未经测试的。但是像这样...

$('.message-text:nth-child(1)').each(function(){ 
$(this).nextAll('.message-text').andSelf().wrapAll("<div class='message-text-wrapper'></div>"); 
}): 
+0

几乎可以工作。它创建两个消息文本包装器,另一个包装一切。 – user995317

+0

只需稍做更改即可完成工作。谢谢! – user995317

+0

你有什么变化,所以我可以更新我的答案? –

4

使用jQuery's wrapAll() function

$('.message-text').wrapAll("<div class='message-text-wrapper' />"); 

这里的a working fiddle

编辑:

按照您的指示在评论,下面的代码将包装在div每个单独的元素。小提琴也进行了更新。

$('.message-text').wrap("<div class='message-text-wrapper' />"); 
+0

是的,我实际上已经尝试过,但是它包裹了所有内部包装。在输出中我想要的是多个不同的包装。 – user995317

+0

@ user995317,我误解了要求。见上面的编辑。 –