Learning
Learning

Reputation: 20051

nth element using jquery

I need to add hr tag after fourth element which is working but but it broke my jquery which removes padding-right from the fourth element.

Without hr tag my jquery works fine

 $("div.container  > div:nth-child(4n+4)").css("padding-right", "0px");

but when i add


tag it just breaks the jquery in this case it removes padding from 4 div and 7th div as it counts
also as a child item.

I also tried

$("div.container > div.image-wrapper:nth-child(4n+4)").css("padding-right", "0px");

this didn't work event.

How can i modify it so that it only counts div's with class image-wrapper as it child's and remove padding from 4 & 8th div only.

HTML

<div class="container">
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>
    <hr class="video-divider-line">
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>
    <div class="image-wrapper"></div>

</div>

Upvotes: 0

Views: 88

Answers (3)

Ram
Ram

Reputation: 144739

Try this:

var $divs = $("div.container > div.image-wrapper");

for (var i = 3; i < $divs.length; i+=4) {
   $divs.eq(i).addClass('zero-padding');
}

http://jsfiddle.net/RKUae/

Or:

.zero-padding { padding-right: 0 }

$("div.container > div.image-wrapper").addClass(function(i) {
    if (++i % 4 === 0) return 'zero-padding';
});

Upvotes: 2

dc5
dc5

Reputation: 12431

Try nth-of-type

$("div.container  > div:nth-of-type(4n+4)").css("padding-right", "0px");

Or

$("div.container  > .image-wrapper:nth-of-type(4n+4)").css("padding-right", "0px");

Upvotes: 1

Rituraj ratan
Rituraj ratan

Reputation: 10388

$("div.container .image-wrapper:eq(3),div.container .image-wrapper:eq(6)").css("padding-right", "0px");

reference eq

Upvotes: 1

Related Questions