开发者

Wrapping divs in to wrapper div with jQuery

开发者 https://www.devze.com 2023-04-12 20:01 出处:网络
Like the title says, I would need to wrap some divs inside of of div. Here\'s the HTML. <div class=\"something1 message\">

Like the title says, I would need to wrap some divs inside of of div. Here's the HTML.

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

Now what I would like to the output to be:

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

Basically that all "message-text" spans that are inside of invidual message div would we wrapped inside message-text-wrappe div.

Hopefully you understant.


Use jQuery's wrapAll() function:

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

Here's a working fiddle.

Edit:

Per your instructions in the comments, the code below will wrap each individual element in the div. The fiddle has been updated as well.

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


Does this work? It's untested. But something like this...

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

精彩评论

暂无评论...
验证码 换一张
取 消