- This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
Viewing 5 posts - 1 through 5 (of 5 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Removing last comma on list item using jQuery
Howdy All,
I’ve successfully added commas to a list items using the jQuery plugin below.
$(document).ready(function(){
$("#selector-name li").append(",");
});
But what I didn’t think about was excluding a comma on the last list item. Anyone with an inclination on what i’m missing in my plugin code that’ll take care of that?
Appreciate the help.
Maybe something like so:
$(document).ready(function(){
$("#selector-name li").not(":last").append(",");
});
Update (solved): Includes Pseudo-Class :last-child instead of :last
$(document).ready(function(){
$("#selector-name li").not(":last-child").append(",");
});
Figured it out! Very easy to. Instead of using the Pseudo-Class of :last, use the Pseudo-Class :last-child. This will target the last <li> of each parent element it belongs to. So if you have multiple <ol>, <ul> it’ll target the last <li> of each of those and NOT the last <li> in the HTML document. Wheww! Hope this was helpful to all like it was for me. So simple to, Doh!
Funny – I was going to suggest that but didn’t want to waste your time due to my lack of jQuery knowledge. Glad you got it sorted and posted the solution back!
I’m pretty sure :first-child only has full browser support and :last-child doesn’t support IE at all. A better solution might be to use jQuery’s size() and have a variable called int and use the .each method to loop through your list items and check if int is less than the size.
Howdy guys! It definitely is working on IE the pseudo-class :last-child. Well in terms of jQuery manipulating the DOM in order to make it work in IE. IE may not understand what that element that jQuery created but it goes ahead and renders it as the DOM commands it. At least that’s how I understand it. Either way thanks for chiming in.