开发者

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 h开发者_如何学Pythonere, since there are text nodes (the commas) in between each link and these are not selected by that query.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜