Home » Jquery » javascript – How do I set data attribute value by the index of element in jQuery?-Exceptionshub

javascript – How do I set data attribute value by the index of element in jQuery?-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have multiple sibling elements, some that are added dynamically and others manually or using JS. Each one has a data attribute of “data-sec_number” with a number value that increases by one for each new element down the page. At the moment I am manually writing these in.
E.g.

<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>

How can I get the value of attribute “data-sec_number” to match the index of the element .resource_sec within the .container element? E.g. the 3rd .resource_sec element will always have a “data-sec_number” value of 3.
I also have the child element of .resource_sec called .sec_number, which has the same data attribute that should mirror the parent.

The JS I have been trying to use 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>
How to&Answer:

The meaning of this line

$('.resource_sec').attr('data-sec_number', index);

is to set the attribute value. to select (query) a specific index please use:

$('.resource_sec[data-sec_number=' + index + ']')

or

$(`.resource_sec[data-sec_number=${index}]`)

If you support ES6


UPDATE:

To add a new element in jQuery you may use:

var container = $('.container')
var newElement = $('<div class="row resource_sec"></div>').appendTo(container)

Then, you can fetch the new element index by passing it to the index method,according to Jquery documentation:

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

var index = container.index(newElement)

To append index to the new element attribute:

newElement.attr('data-sec_number', index)