views:

58

answers:

2

I have a page which essentially looks like this:

<div id="foo">
    <a>One</a>, <a>Two</a>, <a>Three</a>, <a>Four</a>
</div>

Extra attributes removed for the sake of brevity.

There could be any number of links inside the div. What I want to do is to hide all the links after the n th one and add a "Show the rest" link. Basically, for that to happen (as far as I can see), I'd need to be able to transform it to look like this:

<div id="foo">
    <a>One</a>, <a>Two</a>, <a>More...</a>
    <span style="display: none"><a>Three</a>, <a>Four</a></span>
</div>

How would you wrap the links in another element?

Note that the obvious approach ($('#foo a:gt(1)').wrapAll('<span>')) will not work here, since there are text nodes (the commas) in between each link and these are not selected by that query.

A: 

For a start, maybe you should rewrite the element to be like this:

<div id="foo">
  <span><a>One</a></span>
  <span>, <a>Two</a></span>
  <span>, <a>Three</a></span>
  <span>, <a>Four</a></span>
</div>

Then you can easily show or hide any foo childrens that you want easily with :gt filter.

Donny Kurnia
+3  A: 

Try this, adjust the index based on being 2n since every text node counts as one now as well:

$(function() {
  var n = 4;
  $('#foo').contents()
    .filter(function(index){ 
         return index > n && ((this.nodeType==3)||(this.nodeName=="A"))})
    .wrapAll('<span style="background: red;">');
});
Nick Craver
Why this approach? nickf simply wanted to hide all 'a' elements after an index.
patrick dw
@patrick: that's right, including the `,` text nodes.
Crescent Fresh
@patrick - Look at the markup again...hiding all the `<a>` elements would leave lots of commas :)
Nick Craver
Yes, you're right. It just hit me. Dang. I hate down-votes! :o)
patrick dw