Nick
Nick

Reputation: 11

Jquery - How to set an attribute with index starting at 1 instead of 0?

$('ul li a').each(function(index, element){$(element).attr("href", "#img"+index);});

I'd like my list item links to start with the href as "#img1" and count up from there for each item. The code I have will start at "#img0" which doesn't work for what I'm trying to accomplish.

Thanks for any help.

Upvotes: 1

Views: 3933

Answers (2)

Nick Craver
Nick Craver

Reputation: 630439

Since jQuery 1.4+, .attr() takes a function directly, like this:

$('ul li a').attr("href", function(index) { return "#img" + (index+1); });

The index is still 0 based, so just add 1 when using it.

Upvotes: 5

Justin808
Justin808

Reputation: 21512

Try:

$('ul li a').each(function(index, element){$(element).attr("href", "#img"+(index+1));});

Upvotes: 0

Related Questions