maze
maze

Reputation: 215

Increment attribute value (int) for each element using jquery

i have an unknown number of section elements:

<section id="foo">
...
</section>

<section id="bar">
...
</section>

For each section which is present I need to add an attribute "data-serial" which is an integer starting at 0 and being incremented by 1 for each section present, for example the above would turn into:

<section id="foo" data-serial="0">
...
</section>

<section id="bar" data-serial="1">
...
</section>

<section id="bla" data-serial="2">
...
</section>
...

How can I achieve this using jQuery?

Thanks

Upvotes: 3

Views: 32021

Answers (4)

Chris
Chris

Reputation: 27609

A modified version of James Allardice's answer taking advantage of the rarely used parameters that each passes to the function it is given. The first parameter is the index of the current iteration of the loop.

http://api.jquery.com/each/

$("section").each(function(index) {
   $(this).attr("data-serial", index);
});

Upvotes: 12

Tim Rogers
Tim Rogers

Reputation: 21713

$("section").each(function(i, e) { $(e).attr("data-serial", i) });

Upvotes: 1

MikeM
MikeM

Reputation: 27405

something like

var i = 0;
$('section').each(function() {
    $(this).data('serial', i++);
});

Upvotes: 1

James Allardice
James Allardice

Reputation: 165971

var current = 0;
$("section").each(function() {
   $(this).data("serial", current);
   current++;
});

This loops through all section elements in the document, and attaches the value of current to each element using the jQuery data method.

Upvotes: 17

Related Questions