3

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

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

Comments

12

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);
});

4 Comments

Everybody always forgets those poor little parameters. Nice to actually see a use for it for a change. ;-)
Yeah, the wonders of jQuery, making everything even easier than you think at first!
for some reason this doesnt work. it seems the index value is not set for the data-serial attribute
@maze: weird. I created a fiddle (jsfiddle.net/chrisvenus/3FbWN) and when I use firebug to examine the generated html the attributes are showing up... Though having just seen the accepted answer that isn't setting the data-serial attribute but updating an internal data element. I assume this is what you in fact wanted?
1

something like

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.