简体   繁体   English

如何用jQuery包装div标签中的各种元素?

[英]How to wrap various elements in a div tag with jQuery?

I have an html structure that looks like this: 我有一个看起来像这样的html结构:

<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: 总而言之,它只是一些包含在它们下面的内容的标题,我只需要在div中的标题标记下方的所有内容,如下所示:

<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? 我已经尝试过使用jQuery的.wrap函数,但没有运气,因为标题标签下面可以有多个类型元素,我发现这个问题: jQuery包装div的元素集非常相似但是不能适应它成为我需要的,任何人都可以帮助我吗?

Thanks in advance! 提前致谢!

Do this: 做这个:

$(document).ready(function () {
    $('h5').each(function () {
        $(this).nextUntil('h5').wrapAll('<div class="box"></div>');
    })
})

You can try this: 你可以试试这个:

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

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

Try this 尝试这个

var $div;
$("h5").each(function(){
  $div = $("<div />");

  if($(this).nextAll("h5").length){
   $(this).after($div.append($(this).nextUntil("h5")));
  }
  else{
    $(this).after($div.append($(this).siblings()));
  }

});

I would just stick a div in the page after the h5, and manually insert the elements into it. 我会在h5之后在页面中粘贴div,然后手动将元素插入其中。

Assuming that everything is inside something, like the body tag (untested!): 假设一切都在内部,例如body标签(未经测试!):

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

var children = $(document.body).children(),
    $child
    $div;

for(var x = 0, child; child = children[x++];) {
    $child = $(child);
    if($child.is('h5')) {
        $div = $('<div></div>').after($child);
    } else {
        $child.appendTo($div);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM