Javascript jQuery将元素包装在许多元素周围

Javascript jQuery将元素包装在许多元素周围,javascript,jquery,Javascript,Jquery,我有下面的html,想用javascript或jquery在所有li的周围加上一个div(没有定义li的数量) 试验 ... 结果应该是这样的 <div class='example1'> <div class='example2'> <h1>Test</h1> <div class='example3'> <div class='lis'> <li></li>

我有下面的html,想用javascript或jquery在所有li的周围加上一个div(没有定义li的数量)


试验
  • ...
  • 结果应该是这样的

    <div class='example1'>
      <div class='example2'>
      <h1>Test</h1>
      <div class='example3'>
      <div class='lis'>
        <li></li>
        <li></li>
        ...
        <li></li>
        <li></li>
      </div>    
    </div>
    
    
    试验
    
  • ...
  • 我无法在现有html中添加任何其他内容:(

    你能帮我吗?

    你可以使用:

    $('li').wrapAll('');
    
    但是HTML规范规定了这一点,而不是
    DIV

    您可以使用将匹配元素集包装到另一个元素中

    使用以下方法:

    (function($) {
    $.fn.customWrap = function(wrapper) {
        if (!this.length) return this;
        var wrap = $(wrapper),
            sel = this.selector || this.get(0).nodeName.toLowerCase();
        return this.each(function() {
            var more = $(this).next(sel).length;
            console.log(this,more);
            $(this).replaceWith(wrap).appendTo(wrap);
            if (!more) wrap = $(wrapper);
        });
    }
    })(jQuery);
    
    然后像这样调用:

    $(function() {
    $('li').customWrap('<div class="lis"></div>');
    });
    
    $(函数(){
    $('li').customWrap('');
    });
    
    或者您可以使用,但这将在页面中包装所有
    li
    。而不是连续的


    请参阅差异和

    这甚至不是有效的标记!抱歉,我想让它尽可能简单,我将添加两个div和一个ulNo:这将分别包装它们。请参阅我的答案。谢谢:)我没有找到wrapAll方法。这对我来说真的很好!。。。为什么不使用现有的功能?我看过你的编辑。但通常选择器不仅仅是“li”,而是一个足够具体的选择器。。。
    (function($) {
    $.fn.customWrap = function(wrapper) {
        if (!this.length) return this;
        var wrap = $(wrapper),
            sel = this.selector || this.get(0).nodeName.toLowerCase();
        return this.each(function() {
            var more = $(this).next(sel).length;
            console.log(this,more);
            $(this).replaceWith(wrap).appendTo(wrap);
            if (!more) wrap = $(wrapper);
        });
    }
    })(jQuery);
    
    $(function() {
    $('li').customWrap('<div class="lis"></div>');
    });