JQuery - select everything except the last list (from multiple lists).

I wonder is this the most elegant and efficient way to do this?

I have several tag lists, and through CSS I want the tags to be displayed inline (display: inline) and separated by a comma. The task I am experiencing is to add commas to all but the last element of the list in each ul.tagList:

<ul class="outerList"> <li> <div class="innerContainer"> <ul class="tagList"> <li>Tag A</li> <li>Tag B</li> <li>Tag C</li> </ul> </div> </li> <li> <div class="innerContainer"> <ul class="tagList"> <li>Tag D</li> <li>Tag E</li> <li>Tag F</li> </ul> </div> </li> </ul> 

To add commas to all the elements of the ul.tagList list, but the last one I use:

  $('ul.tagList').children(':not(:last-child)').append(','); 

and it gives:

Tag A, Tag B, Tag C

Tag D, Tag E, Tag F

Is this the best way to do this?

Also why: not (: last-child) works, but not: not (: last) in this context?

Thank you very much for your help + explanation.

Prembo

+4
source share
2 answers

:last does not work in this context, since it will only correspond to one element, namely the last .

last-child can match more elements, one for each parent.

Your code looks pretty good using . not () instead of querying with sizzle may improve performance a bit.

 $('ul.tagList').children().not(':last-child').append(','); 
+8
source

This was published a long time ago, but thought it was good to publish for anyone else (for example, for me) who views this post as a link. I did jsPerf for the two cases above, plus one I added myself using .prevAll ()

 $('.tagList').children(':last-child').prevAll().css('background-color', 'yellow'); 

A little bit faster

http://jsperf.com/all-but-last-performance

+1
source

Source: https://habr.com/ru/post/1313353/


All Articles