Reputation: 746
Trying to find an element with jquery and have hit a roadblock.
I have a variable with another elements id stored in it. I am trying to find the corresponding anchor link with that stored variable as it's href. Then get the anchor link(href) directly before that anchor.
So basically finding the list item anchor link previous to the list item anchor link with the id of the displayed div
.html
<li><a href="#example" class="links">example</a></li>
<li><a href="#example1" class="links">example</a></li>
<li><a href="#example2" class="links">example</a></li>
<li><a href="#example3" class="links">example</a></li>
<div id="example" class="divs"> random stuff </div>
<div id="example1" class="divs open"> random stuff </div>
<div id="example2" class="divs"> random stuff </div>
<div id="example3" class="divs"> random stuff </div>
.js
$('.previous').click(function(e) {
e.preventDefault();
var exampleId = $('.divs.open').attr('id');
var anchorPrev = $('.links').find('href');
});
Upvotes: 1
Views: 9303
Reputation: 59377
Try this:
$('.previous').click(function (e) {
e.preventDefault();
var exampleId = $('.divs.open').attr('id');
var selector = "a.links[href='#" + exampleId + "']";
var link = $(selector);
var prev = link.parent().prev().find('a.links');
});
What that does is tell jQuery to find an anchor tag with the specified value of it's href
attribute.
You can see the docs here: http://api.jquery.com/attribute-equals-selector/
EDIT Ok I see. I've edited the code sample above to reflect the original question regarding getting the previous link. Note however that this won't really work for the first element in the list.
The problem is that your a
tags are children of li
tags. So calling prev()
directly on the a
won't work as it has no siblings. However, the parent li
tag does have siblings, so you can call prev()
on that and then get the a.links
element contained within.
Here's a jsFiddle that I whipped up to test: http://jsfiddle.net/kHnju/
Upvotes: 3