Emin
Emin

Reputation: 371

target sibling of 'this', with nth-child

I'm trying to target the nth sibling of a clicked item. Basically to target next element that is nth(4n+4), to be able to insert a new element after that, kind of like on a "new line".

$("li").click(function () {
    $(this).next('li:nth-child(4n+4)').after('<li class="full">new full width item</li>');
});

It's the .next('li:nth-child(4n+4)') that doesn't seem to work.

It's a bit hard to explain, but you will understand what I mean here: http://jsfiddle.net/hYE7e/1/

Upvotes: 0

Views: 275

Answers (2)

mishik
mishik

Reputation: 10003

This is actually working fine, but after() will only be executed, when the very next li is 4n+4 child. I.e. right from the start, it will work fine if you click on 3 or on 7. Right after you clicked on 3, the 7th one will stop working and 6th one will work instead, because 7 has now become 8th element.

A bit clumsy update: http://jsfiddle.net/hYE7e/3/

$("ul li:nth-child(4n)").addClass("last-in-line");
$("li").click(function () {
    $(this).nextAll("li.last-in-line").andSelf(".last-in-line").filter(":first").after('<li class="full">new full width item</li>');
});

andSelf(".last-in-line").filter(":first") to ensure that clicking on 4th, 8th, etc elements will work.

Update:

After discussion in comments, I think I have it: http://jsfiddle.net/hYE7e/7/

With custom filter:

$("li").click(function () {
    var myIndex = $("li:not(.full)").index($(this)); // Save our position in a row
    $(this)
      .nextAll("li:not(.full)")
      .andSelf()
      .filter(function(index){  // Get 4n'th lis from 'not(.full)' set
          return (index + myIndex + 1) % 4 == 0;  
      })
      .add("li:last")  // Make sure last rows will work
      .first()         // Only add 'li' after first matching element
      .after('<li class="full">new full width item</li>');
});

Upvotes: 2

Sebastian vom Meer
Sebastian vom Meer

Reputation: 5241

I think you want to filter all ucoming siblings, not only the next one, right? Perhaps this is what you want:

$(this).nextAll('li:nth-child(4n+4)').first().after('<li class="full">new full width item</li>');

See my updated Fiddle here.

Upvotes: 2

Related Questions