Help with relatively simple addClass during loop

Help with relatively simple addClass during loop
0.0 0


So, what i’m trying to do is, each time I pass through the loop I add a class to a randomized within the set. What i’m expecting to see is that one of the words “coffee” is orange depending on what the random number generator chooses. Is this even possible, been struggling for a few days and could use some help.

Thank you in advance!!


Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at

With your current questions, we don’t have enough context to know what you already know or don’t know, so it is impossible to guide you without just telling you the answer (which we won’t do).

Happy coding :slight_smile:


You are not understanding how the nth-child selector works. When you write


You are targeting the 1st child element of the parent of ul#container. The parent of ul#container is the document’s body element. The 1st child element of the body is the ul element with id=“container”, so the entire ul element will have an orange background.


@randelldawson Thanks for the reply. You’re right, I think I don’t understand how that selector works, but mostly in context of when i’m traversing through a loop.

$(‘ul#container span:nth-child(2)’, i).addClass(‘last’);

If i’m appending 3 during a loop I would think this would update every 2nd with my class. I know that isn’t working because when I change it to nth-child(4), it goes to the second set of .

Am I thinking about the nth-child selector wrong, or am I thinking of the context in the wrong way?

Thanks again for the reply/sharing of knowledge


What is your ultimate goal? Are you wanting to make the nth set of 3 spans orange? Or are you wanting to make the nth span element of each set of 3 spans orange? When I refer to nth, I mean some predetermined (randomized) number.


The second option. The nth span element of each set orange.


Then you need to wrap each of the 3-span sets in another container. Then you will be able to use $(‘span:nth-child(1)’).addClass(‘half’); with 1 representing the random span in each set to turn orange. The most logical choice of container would be the li element since the overall container is a ul element.


+1 appreciate your help, friend