Reputation: 2701
i am working on some list items and on readicon class click i am not able to capture the href value of a with class bookpath. in this case (google.com)
here is the code
<li >
<div class="overlay">
<span id="Title">Yeah Dude</span>
<img class="readIcon" src="images/read.png" />
</div>
<a class="bookPath" href="http://www.google.com"><img src="images/bookCovers/asp.net4.5.jpg" alt="book" /></a></li>
i tried this code but it returns undefined.
$(document).ready(function () {
$(".overlay .readIcon").click(function () {
// $(this).('href', 'index.html');
var bookPath = $(this).parents('li').closest('a').href;
alert(bookPath);
});});
thanks a lot.
Upvotes: 0
Views: 96
Reputation: 218812
Get the href atttribute value. use closest
to get outer li and use find
to get the anchor
var bookPath = $(this).closest('li').find('a').attr("href");
Jsfiddle sample : http://jsfiddle.net/4QGHS/5/
Also when doing jQuery selectors, try to be more specific as you can. find('a')
will return all anchor tags. So you better use the classname which you have for elements you are looking for. Try to give a class to your li
element as well.
<li class='bookItem'>
<div class="overlay">
// your other html goes here
<img class="readIcon" src="someImage.jog" />
</div>
<a class="bookPath" href="http://www.google.com"></a>
</li>
now your javascript will be
$(function(){
$(".overlay .readIcon").click(function (e) {
e.preventDefault(); //prevent as needed.
var bookPath = $(this).closest('li.bookItem').
find('a.bookPath').attr("href");
alert(bookPath);
});
});
Jsfiddle sample http://jsfiddle.net/4QGHS/9/
Upvotes: 0
Reputation: 74738
Try with .siblings()
var bookPath = $(this).parent().siblings('a').attr('href');
Try with .find()
var bookPath = $(this).closest('li').find('a').attr('href');
if you want to be more specific then:
var bookPath = $(this).closest('li').find('a.bookPath').attr('href');
Upvotes: 0
Reputation: 15882
There are many ways to do this and this is one.
$(document).ready(function () {
$(".overlay .readIcon").click(function () {
// $(this).('href', 'index.html');
var bookPath = $(this).parent().parent().find("a.bookPath").attr("href");
alert(bookPath);
});
});
Upvotes: 0
Reputation: 14827
Change your query to this:
$(document).ready(function () {
$(".overlay .readIcon").click(function () {
var bookPath = $(this).parents('li').children('a').attr('href');
alert(bookPath);
});
});
Fiddle: http://jsfiddle.net/Lbr4z/
Upvotes: 1