admin管理员组

文章数量:1414628

I have following html and want to wrap with javascript or jquery a div around all li's (its not definied how many li's there are)

<div class='example1'>
  <div class='example2'>
  <h1>Test</h1>
  <div class='example3'>
  <li></li>
  <li></li>
  ...
  <li></li>
  <li></li> 
</div>

The Result should look like

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

I'm not able to add anything else the existing html :(

Can you please help me?

I have following html and want to wrap with javascript or jquery a div around all li's (its not definied how many li's there are)

<div class='example1'>
  <div class='example2'>
  <h1>Test</h1>
  <div class='example3'>
  <li></li>
  <li></li>
  ...
  <li></li>
  <li></li> 
</div>

The Result should look like

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

I'm not able to add anything else the existing html :(

Can you please help me?

Share Improve this question edited Jul 30, 2013 at 10:17 Tushar Gupta - curioustushar 57.1k24 gold badges106 silver badges109 bronze badges asked Jan 11, 2013 at 9:01 Evil_skunkEvil_skunk 3,4124 gold badges33 silver badges45 bronze badges 2
  • 1 This is not even valid markup ! – painotpi Commented Jan 11, 2013 at 9:03
  • sorry, i want to keep it as simple as possible in real I would add two divs and one ul – Evil_skunk Commented Jan 11, 2013 at 9:08
Add a ment  | 

3 Answers 3

Reset to default 8

You could use wrapAll :

$('li').wrapAll('<div class=lis></div>');

But the HTML norm specifies that LI elements are only permitted in UL, OL and MENU, not DIV.

Demonstration

Use this :

(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);

And Invoke like:

$(function() {
$('li').customWrap('<div class="lis"></div>');
});

Or you can use jQuery wrapAll but this will wrap all li in the page.. not the consecutive ones..

See difference here (with wrapAll) and here (custom function)

you can use $.wrap() to wrap the set of matching elements inside another element

本文标签: javascriptjQuery wrap element around a lot of elementsStack Overflow