WM-CR78 WM-CR78 - 1 year ago 35
Javascript Question

JQUERY add class if has class myclassN where N is greater than X alternate width

I have this code:

.div66{width: 66.6%}
.div33{width: 33.3%}

<div class="box1">content</div>
<div class="box2">content</div>
<div class="box3">content</div>
<div class="box4">content</div>
<div class="box5">content</div>
<div class="box6">content</div>
<div class="box7">content</div>
<div class="box8">content</div>
<div class="box9">content</div>
<div class="box10">content</div>

I need to obtain below with a jQuery function.

.div66{width: 66.6%}
.div33{width: 33.3%}

<div class="box1">content</div>
<div class="box2">content</div>
<div class="box3 div66">content</div>
<div class="box4 div33">content</div>
<div class="box5 div33">content</div>
<div class="box6 div66">content</div>
<div class="box7 div66">content</div>
<div class="box8 div33">content</div>
<div class="box9 div33">content</div>
<div class="box10 div66">content</div>

If boxN is greatest than 3 apply divXX class, and after first div66 toggles 2x div33 and 2x div66


I solved using CSS and nth-child

.box:nth-child(n+3) {width: 33.3%}
.box:nth-child(4n+3), .box:nth-child(4n+6) {width: 66.6%}

<div class="box box1">content</div>
<div class="box box2">content</div>
<div class="box box3">content</div>
<div class="box box4">content</div>
<div class="box box5">content</div>
<div class="box box6">content</div>
<div class="box box7">content</div>
<div class="box box8">content</div>
<div class="box box9">content</div>
<div class="box box10">content</div>

Answer Source

You can do it by,

var elems = $("div").filter(":nth-child(3)").addClass("div66").nextAll().get(),isThree = true;
for (var i = 0; i < elems.length; i += 2) {
  $(elems[i]).add(elems[i + 1]).addClass(isThree ? "div33" : "div66");
  isThree = !isThree;