I have a simple difficulty scale. As I only know some basics of jQuery and JavaScript I don’t know what I’m searching for. I want to add the class active to the item based on the data-attribute of the parents element.
Below two examples how it should look like at the end.
<div class='difficulty-wrapper' data-difficulty='1'>
<span class='difficulty-item active'></span>
<span class='difficulty-item'></span>
<span class='difficulty-item'></span>
<span class='difficulty-item'></span>
</div>
<div class='difficulty-wrapper' data-difficulty='4'>
<span class='difficulty-item active'></span>
<span class='difficulty-item active'></span>
<span class='difficulty-item active'></span>
<span class='difficulty-item active'></span>
</div>
2
Answers
This script uses jQuery to iterate through each .difficulty-wrapper element, retrieves the data-difficulty value, and adds the "active" class to the corresponding number of .difficulty-item elements within that wrapper. The :lt() selector is used to select elements with an index less than the specified value (in this case, the difficulty level).
You may not need to actually add a class at all. You can select the child divs directly based on the attribute and set the styling on the elements from there.
Here’s an example targeting the
difficulty="4"
set of elements: