nickf
nickf

Reputation: 545995

Wrap text and elements in another element using jQuery

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.

Upvotes: 2

Views: 491

Answers (2)

Nick Craver
Nick Craver

Reputation: 630359

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;">');
});

Upvotes: 3

Donny Kurnia
Donny Kurnia

Reputation: 5313

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.

Upvotes: 0

Related Questions