Oto Shavadze
Oto Shavadze

Reputation: 42753

last-child element from class

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

Answers (3)

Travis J
Travis J

Reputation: 82267

Perhaps like this:

$(".my_div").each(function(ind,el){
 if(el == $(".my_div:last")[0]) return true;//continue;
 $(el).css({color: "#090"});
});

http://jsfiddle.net/mys3k/1/

Upvotes: 0

netdjw
netdjw

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

T.J. Crowder
T.J. Crowder

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

Live Example | Source

Upvotes: 11

Related Questions