Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Select all but last list (from multiple lists.)

I'm wondering if this is the most elegant and efficient way of doing this?

I have multiple 'tag' lists, and through CSS, I want the tags to appear inline (display: inline) and be comma-separated. The challenge that I'm having is to append commas to all but the last list item 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 append commas on all the ul.tagList list items, but the last, I use:

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

and this produces:

Tag A, Tag B, Tag C

Tag D, Tag E, Tag F

Is this the best way of doing this?

Also why does :not(:last-child) work but not :not(:last) in this context?

Thanks very much for your help + explanations.

Prembo.

like image 330
Prembo Avatar asked Jan 21 '23 21:01

Prembo


1 Answers

:last does not work in this context, because it will only match one element, namely the last.

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

Your code looks pretty fine, using .not() instead of querying with sizzle might improve performance slightly.

$('ul.tagList').children().not(':last-child').append(',');
like image 66
jAndy Avatar answered Jan 31 '23 08:01

jAndy