0

I've tried searching for an answer, but without joy - I'm new to JS (as in started learning last week), and I've hit a problem that I don't even know where to look to start solving.

I have a div with the id container, inside that div are lots of little divs with the class item. I want to give those .items the additional classes of tile1 for the first div, tile2 for the second, tile3 for the third, tile4 for the fourth, then going back to tile1 for the fifth, tile2 for the sixth etc.

The amount of .tiles in the #container will be dynamically generated, possibly with waypoints using infinite scroll, which makes me want to use javascript to do this rather than manually type these classes in.

Can anyone give me some pointers?

Thanks!

1
  • Uh... why? The psuedo-class :nth-child(4n+1) will get the first, fifth, ninth... You can also do 4n+2, 4n+3 and 4n. Commented Dec 12, 2013 at 17:59

3 Answers 3

1

You can use .addClass() method and modulus operator:

$('#container .item').addClass(function(i) { 
    return 'tile' + (i % 4 + 1);
});

http://jsbin.com/evuFOqUd/3/edit

Or in case that you are not using jQuery:

[].forEach.call(
  document.querySelectorAll('#container .item'), 
  function(el, i) {
    el.classList.add('tile' + (i % 4 + 1));
  }
);

Which only works in modern browsers.

Sign up to request clarification or add additional context in comments.

Comments

1

Here's a jsbin demo


jQuery .each is your friend

$("#container .item").each(function(idx, elem) {
  $(elem).addClass("tile" + (idx + 1));
});

EDIT

I did not see that you wanted the tile numbers to wrap

$("#container .item").each(function(idx, elem) {
  $(elem).addClass("tile" + (idx % 4 + 1));
});

2 Comments

Thank you so much. Despite the fact that I can see it work in your JSbin, for some reason it won't work for me in my own code - probably because of myu inexperience. I've tried putting $(document).ready (function() { [your code] )} and still no luck.
@Wilf, not sure what to tell you there. You could have other JavaScript errors on the page? Perhaps post another question once you identify the problem.
0

A non-jQuery approach (pardon the pseudo-code):

var breakAfter = 4; // Reset iterator after reaching 5 runs
var iterator = 0;
var elementList = document.querySelector(".myk00lElementClass"); // Your DOM nodes
for (element in elementList) { 

    element.classList.add('dynamicClass_' + iterator);

    // Reset dynamic class number if we have reached arbitrary length above
    if (iterator >= breakAfter) {
        iterator = 0;

    // Or, keep on truckin'
    } else {
        iterator++;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.