views:

48

answers:

2

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

+3  A: 
$('.next-video').each(function(index) {
    $(this).attr('href', '#post' + (index + 2));
});
Darin Dimitrov
Can you tell me why you chose method way instead of selector way to select each element of .next-video?
Braveyard
@Braveyard, I don't understand your question.
Darin Dimitrov
Hey, doesn't seem to target the .nextvideo class as its not adding the href value. This is the live sample: http://www.warface.co.uk/clients/detail-shoppe/test-scroll
Rob
@Braveyard There no difference between both ways I guess.
Andy
@Andy, I remember I was struggling to make selector way work in Mozilla but function way was working strangely. That's why I asked it. It could be a bug tho but I was very frustrated back then :)
Braveyard
@Braveyard yes, it could be a jquery bug. There are a lot of bugs in jquery.
Andy
@Andy, well then. I hope they fix them as soon as possible. Because I totally integrate my life into jQuery sometimes :)
Braveyard
+3  A: 

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');
});
Nick Craver
You said "cheaper to run" what do you mean by saying that? It is more time efficient?
Braveyard
@Braveyard - You're not creating another jQuery object, you're setting DOM properties so it's cheaper in the fact there's less work to be done...so yes it should be more time efficient as well, unless there's something very odd going on. jQuery objects are arrays of references to DOM elements, we're just looping over that array setting properties...as opposed to turning each reference in the array *also* into a jQuery object just to do some work...if you don't *need* a jQuery object, skip the middle man and save some CPU, as you see in the first code block, it's also a bit more terse :)
Nick Craver