I am dealing with multiple sibling elements that are added dynamically or manually using JS. Each element has a data attribute called "data-sec_number" with a number value that increments by one for each subsequent element down the page. Currently, I am manually assigning these values. For example:
<div class="container">
<div class="row resource_sec" data-sec_number=1>
<div class="content sec_number" data-sec_number=1></div>
</div>
<div class="row resource_sec" data-sec_number=2>
<div class="content sec_number" data-sec_number=2></div>
</div>
<div class="row resource_sec" data-sec_number=3>
<div class="content sec_number" data-sec_number=3></div>
</div>
</div>
I am trying to figure out how to automatically set the value of the "data-sec_number" attribute to match the index of the .resource_sec element within the .container. For instance, the 3rd .resource_sec element should always have a "data-sec_number" value of 3. Additionally, I have a child element of .resource_sec called .sec_number, which also has the same data attribute that should reflect the value of its parent.
The JS code snippet I have been experimenting with is:
var items = $('.container .resource_sec');
var lastItem = $('.container .resource_sec:last');
var index = items.index(lastItem);
$('.resource_sec').attr('data-sec_number', index);
$('.sec_number').attr('data-sec_number', index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row resource_sec" data-sec_number=1>
<div class="content sec_number" data-sec_number=1></div>
</div>
<div class="row resource_sec" data-sec_number=2>
<div class="content sec_number" data-sec_number=2></div>
</div>
<div class="row resource_sec" data-sec_number=3>
<div class="content sec_number" data-sec_number=3></div>
</div>
</div>