I need a little help adding a class to multiple elements. For example, if I have 5 divs inside a container and placing a number 4 that will be sent by post in the script, the class will be added to only the first 4 elements. and if I put a 3, the class will be added to only the first 3 elements.
I hope you can help me with a part of the code that I don't know much about.
I hope to be of help. I also tell you that for future questions you should include some code that you have already done. It is important. Since I don't have any samples of your code, the selectors I'm going to use in the functions are set without ids.
Saving you the jQuery part, the concept can be the following.
First of all you have a div that has N div children. These children can be obtained with a
querySelectorAll
, like this:const childrenDivs = document.querySelectorAll('#container > div');
This returns you a NodeList , which is iterable through the
.forEach()
.This method passes its callback the following values:
element
, ,elementIndex
andobj
, the latter being the original NodeList.Knowing this, we could make a function that iterates over the elements of this NodeList, check if its index is correct and operate on it.
Thus we could have this case: