如何使用jQuery将各种元素包装在div标签中? [英] How to wrap various elements in a div tag with jQuery?

查看:42
本文介绍了如何使用jQuery将各种元素包装在div标签中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 html 结构:

Title
<p>内容

<ul><li>项目</li><li>项目</li><p>内容

<h5>标题</h5><p>内容

<ul><li>项目</li><li>项目</li><p>内容

总而言之,它只是一些标题,其下方有内容,我只需要像这样的 div 中标题标签下方的所有内容:

Title
<div><p>内容

<ul><li>项目</li><li>项目</li><p>内容

我尝试使用 jQuery 的 .wrap 函数,但没有运气,因为标题标签下方可以有多个类型元素,我发现了这个问题:jQuery 在 div 中包装元素集,这非常相似,但无法适应我需要,有人可以帮我吗?

提前致谢!

解决方案

你可以试试这个:

http://jsfiddle.net/GGjXN/1/

$(function() {$('h5').each(function(i, e) {$(e).nextUntil('h5').wrapAll('

');});});

I have an html structure that looks like this:

<h5>Title</h5>
<p> Content </p>
<ul>
    <li>Item</li>
    <li>Item</li>
</ul>
<p> Content </p>

<h5>Title</h5>
<p> Content </p>
<ul>
    <li>Item</li>
    <li>Item</li>
</ul>
<p> Content </p>

In summary it's just some headers with content below them, I just need everything below the header tags in a div like this:

<h5>Title</h5>
<div>
    <p> Content </p>
    <ul>
        <li>Item</li>
        <li>Item</li>
    </ul>
    <p> Content </p>
</div>

I've tried using the .wrap function of jQuery but no luck since there can be multiple types elements below the header tags, I found this question: jQuery wrap sets of elements in div which is very similar but haven't been able to fit it into what I need, can anyone help me?

Thanks in advance!

解决方案

You can try this:

http://jsfiddle.net/GGjXN/1/

$(function() {
    $('h5').each(function(i, e) {
        $(e).nextUntil('h5').wrapAll('<div>');
    });
});

这篇关于如何使用jQuery将各种元素包装在div标签中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆