Rob
Rob

Reputation: 1495

Add href to links dynamically

I have a series of horizontal div boxes that I need to add the relevant href to link to the next one with anchorlinks. As they are produced dynamically I need to add the href with JavaScript.

The desired effect will be:

<div id="post1">
<a class="next-video" href="#post2">NextVideo</a>
</div>

<div id="post2">
<a class="next-video" href="#post3">NextVideo</a>
</div>

Added the script

$('.next-video').each(function(index) {
    $(this).attr('href', '#post' + (index + 2));
});

but doesn't seem to target the .next-video class, this is the live version: http://www.warface.co.uk/clients/detail-shoppe/test-scroll

Many thanks

Upvotes: 0

Views: 930

Answers (2)

Nick Craver
Nick Craver

Reputation: 630597

You could do something like this using .attr():

$("a.next-video").attr('href', function(i) {
  return '#post' + (i+2);       
});

Since jQuery 1.4+, .attr() takes a function making this very clean (and cheaper to run).

Or if you don't know the post number (e.g. they're just not in numerical sequence), you can get it from the next <div>, like this:

$("a.next-video").attr('href', function(i) {
  return '#' + $(this).parent().next("div[id^='post']").attr('id');
});

Upvotes: 3

Darin Dimitrov
Darin Dimitrov

Reputation: 1039418

$('.next-video').each(function(index) {
    $(this).attr('href', '#post' + (index + 2));
});

Upvotes: 3

Related Questions