user1005793
user1005793

Reputation: 2911

How to add a class to an element after a group of elements (based on class) in Jquery?

I have a comment structure like this:

<div class="comment"></div>
<div class="reply"></div>
<div class="reply"></div>
<div class="comment"></div>
<div class="comment"></div>
<div class="reply"></div>
<div class="comment"></div>
<div class="reply"></div>
<div class="reply"></div>

I want to add the class last to the last reply (after comment), so I did something like this:

$('.reply:last').addClass('last');

However, it only applies the last class to the last reply div. Is there a way to add the last class to the last reply after comment so it becomes this:

<div class="comment"></div>
<div class="reply"></div>
<div class="reply last"></div>
<div class="comment"></div>
<div class="comment"></div>
<div class="reply last"></div>
<div class="comment"></div>
<div class="reply"></div>
<div class="reply last"></div>

Thanks!

Also, would it be possible to make it work like this as well, where we have a reply on the top of the page? This could happen if I'm paging and a reply is show first.

<div class="comments">
    <div class="reply last"></div>
    <div class="comment"></div>
    <div class="reply"></div>
    <div class="reply last"></div>
    <div class="comment"></div>
    <div class="comment"></div>
    <div class="reply last"></div>
    <div class="comment"></div>
    <div class="reply"></div>
    <div class="reply last"></div>
</div>

Upvotes: 0

Views: 38

Answers (3)

dSquared
dSquared

Reputation: 9825

Take a look at jQuery's .nextUntil(). With it would could do the following:

$('.comment').each(function(){
    $(this).nextUntil('.comment').filter(':last').addClass('last');
});

JSFiddle Demo Here.

I hope this helps!

Upvotes: 1

user2897690
user2897690

Reputation:

for first case use
$("body .comment:last-child .reply:last-child").addClass("last");

for second case use

$("body").find(".comment").each(function(){
      $(this).find(".reply").last().addClass("last");
)};

check this fiddle. I had moved all reply divs inside respective comments divs to use inheritance property.

Upvotes: 0

rockStar
rockStar

Reputation: 1296

You need to just use the not() function. I tried this, have a look

$('.reply:last').addClass('last');
$('.reply').not($('.reply:last')).removeClass('last');

and a Fiddle sample here.

Upvotes: 0

Related Questions