liebgott
liebgott

Reputation: 89

Select from "value" to "value"

I have this

<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>

and I want select from item 1 to item 5 and wrap them into an UL, and select 6 to 8 and wrapp them in another one.

<ul>
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item">5</div>
</ul>


<ul>
      <div class="item">6</div>
      <div class="item">7</div>
      <div class="item">8</div>
</ul>

How can I do that?. Thank you very much

Upvotes: 3

Views: 132

Answers (4)

Andy E
Andy E

Reputation: 344733

<div> is not a valid child element for <ul>. You should nest <li> elements. As for the selectors, you can use :gt() and :lt():

$('div.item:lt(5)').wrapAll("<div>");
$('div.item:gt(4)').wrapAll("<div>");

Upvotes: 3

Nick Craver
Nick Craver

Reputation: 630587

To create valid HTML here you need to wrap them as list items as well, getting this result:

<ul>
  <li><div class="item">1</div></li>
  <li><div class="item">2</div></li>
  <li><div class="item">3</div></li>
  <li><div class="item">4</div></li>
  <li><div class="item">5</div></li>
</ul>
<ul>
  <li><div class="item">6</div></li>
  <li><div class="item">7</div></li>
  <li><div class="item">8</div></li>
</ul>

Here's jQuery that will do that wrapping/grouping every 5 elements, and the remaining at the end, it'll work for any number of divs you have:

var elems = $("div.item");
for(var i = 0; i < elems.length; i+=5) {
  elems.slice(i, i+5).wrap('<li></li>').parent().wrapAll("<ul></ul>");
}​

You can see a working demo here, this .wrap()s each element in a <li> then wraps the groups using .wrapAll() in <ul>.

Upvotes: 2

Kobi
Kobi

Reputation: 138137

Now, this is far from perfect, but for a start:

function findByText(n){
  return $('.item').filter(function(){return $(this).text() == n});
}

$(function(){
   var from = findByText(2);
   var to = findByText(5);
   $('.item').slice(from.index(), to.index() + 1).wrapAll('<div />');
});

It can be improved in many ways - you may want to convert findByText to a plugin that filters a collection, and you defiantly want to check from and to, and probably call $('.item') only once.
I think it's enough to get you going though.

Working example: http://jsbin.com/ehite4/

Upvotes: 0

Koen
Koen

Reputation: 3683

Something like this will get you there...

$('div.item').slice(0, 5).wrapAll('<ul />');
$('div.item').slice(5).wrapAll('<ul />');

Upvotes: 0

Related Questions