• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1211
  • Last Modified:

How to wrap every nth element with javascript or jQuery

I have a structure like this:

<div>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
        <li></li>
           ... ...
</div>

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?
0
jszeto
Asked:
jszeto
  • 2
2 Solutions
 
COBOLdinosaurCommented:
Just add a <br /> after every third </li>

Why would need scripting to do that?

Cd&
0
 
Julian HansenCommented:
Like this ?
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
  var ul = $('<ul>');
  $('#list li').each(function() {  
    ul.append($(this).detach());
    if (ul.find('li').length == 3) {
      $('#list').append(ul);
      ul=$('<ul>');
    }
  });
  if (ul.length > 0) {
    $('#list').append(ul);
  }
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div id="list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</div>
</body>
</html>

Open in new window

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

Open in new window

Test page : http://jsfiddle.net/9NYtX/2/
0
 
Julian HansenCommented:
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?
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now