How to wrap every nth element with javascript or jQuery

Posted on 2012-09-22
Last Modified: 2012-09-25
I have a structure like this:

           ... ...

I want to use javascript to wrap every 3 <li></li> into a <ul></ul> including what's left no matter it's 1 or 2 <li> left.

Any ideas?
Question by:jszeto
    LVL 53

    Expert Comment

    Just add a <br /> after every third </li>

    Why would need scripting to do that?

    LVL 49

    Assisted Solution

    by:Julian Hansen
    Like this ?
    <!doctype html>
    <script src=""></script>
    <script type="text/javascript">
    $(function() {
      var ul = $('<ul>');
      $('#list li').each(function() {  
        if (ul.find('li').length == 3) {
      if (ul.length > 0) {
    <style type="text/css">
    <div id="list">

    Open in new window

    LVL 81

    Accepted Solution

    You may use :
    while($("div>li").length) $("div>li:lt(3)").wrapAll("<ul />");¿

    Open in new window

    Test page :
    LVL 49

    Expert Comment

    by:Julian Hansen
    Why the B Grade? I think leakim's solution was as complete as it could have been.

    Have you read the grading guidelines for this site?

    Featured Post

    Training Course: Adobe Dreamweaver CC 2015

    Adobe Dreamweaver Creative Cloud is used by web designers and front-end developers and allows you to visualize your site in real-time as you code. This course covers exam objectives for the Adobe Certified Associate (ACA) certification.

    Join & Write a Comment

    Suggested Solutions

    PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
    Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
    In this Micro Tutorial viewers will learn how to create navigation buttons that change on rollover, using CSS (Continuation of the CSS Image Sprite tutorial) Create a parent ID for all the list items       - Specify position: absolute and display: block…
    HTML5 has deprecated a few of the older ways of showing media as well as offering up a new way to create games and animations. Audio, video, and canvas are just a few of the adjustments made between XHTML and HTML5. As we learned in our last micr…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now