Reputation: 42753
given this html
<div class="my_div">a</div>
<div class="my_div">b</div>
<div class="my_div">c</div>
<div>other</div>
I want select all .my_div
element, but not last element from this class, this works not correct
$(".my_div:not(:last-child)").css({
color: "#090"
});
how can select all element from some class, except last element?
Upvotes: 1
Views: 136
Reputation: 82267
Perhaps like this:
$(".my_div").each(function(ind,el){
if(el == $(".my_div:last")[0]) return true;//continue;
$(el).css({color: "#090"});
});
Upvotes: 0
Reputation: 6007
maybe simliest if you use css classes with jQuery for this problem:
// add .nostlasts class to all .my_div divs
$('.my_div').addClass('notlasts');
// remove .nostlasts class from last .my_div
$( $('.my_div')[ $('.my_div').length ] ).removeClass('notlasts');
Upvotes: -1
Reputation: 1074118
:last-child
is exactly that, the last child, not the last child of a given tag.
jQuery offers the :last
selector, which does what you want, but has the cost of being something jQuery does rather than something the browser does. Thus:
$("div.my_div:not(:last)").css({
color: "#090"
});
Upvotes: 11