getting next and prev div id inside a link

I have several divs with unique class 'slide_image', and unique id. Inside each divs I have 2 a links, "#next" and "#prev". what I'm trying to do is to get for each divs the id of the next and prev divs, and attribute the id ty links.

for example for .slide_image id=slide_3

<div id="slide_2" class="slide_image">
    <a href="#slide_3" id="next"></a><a href="#slide_1" id="prev"></a>

<div id="slide_3" class="slide_image">
    <a href="#slide_4" id="next"></a><a href="#slide_2" id="prev"></a>

here is what I've tried but its not working, I think I have a problem with my each() functions :

    var next_link = $(this).next().attr('id');

$( "a#next" ).next().attr("href", next_link)

    var prev_link = $(this).prev().attr('id');

$( "a#prev" ).prev().attr("href", prev_link)

here is a Jsfiddle with all my code :

can anybody help me with this ?

thanks a lot,


What I would do first is what people are suggesting. Change the #next and #prev to classes .next and .prev.

Then loop each .slide_image and find it's index (index will be the current .slide_image element inside it's parent. So the first .slide_image would be 1, the second 2, etc ). Then from here get the next and previous indexes (so 1 would be -1 and 2). We can then use jQuery's eq() to find an element by it's index. Once we have the element we can then get it's id by using attr().

Then simply add these ids to the .next and .prev links.

Take a look at which has a working example.

I didn't check error handling but eq() will return undefined if the element it's looking for doesn't exist (such as an element where it's index is -1). So you could use that to show other slides. Such as if we're on the first slide, should the .prev link to the last slide, or should we simply hide the link preventing them from clicking back?

One thing to note in my code is the use of this in $(".next", this). Basically the second attribute is the context, take a look at this SO post.

Need Your Help

What's the false operator in C# good for?

c# .net syntax

There are two weird operators in C#:

File obtained via WebClient.DownloadFile disappears immediately

c# .net

I've encountered a strange problem, I have a simple service that updates a program, it downloads the file fine, Explorer shows it, but just a second or two after it has been downloaded it disappear...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.