Reputation: 471
I'm having trouble finding ways to get the href value for the last child of a div. Basically, the layout is like this:
<div id="slider">
<div id="slide1" class="slides">
<a href="items/show/1" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide2" class="slides">
<a href="items/show/2" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide3" class="slides">
<a href="items/show/3" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide4" class="slides">
<a href="items/show/4" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide5" class="slides">
<a href="items/show/5" class="link"> <-- trying to get this href value
<h2>Date</h2>
<h3>Title</h3>
</a>
</div>
I'm trying to get the href value of the last sibling of ".link", but i can't. Point me where I did wrong please? So far, here's my jQuery code:
$(document).ready(function(){
var latestUrl = $(".link").siblings(":last").attr("href");
console.log(latestUrl);
});
but the console returns: "undefined"
[UPDATE] I've found the solution to this: I need to wait until the page loads everything, then only I can look for the href attribute of the last child. This example is a gallery of images, so it takes quite some time to load, probably a second after the page loads. So here is the code that sets a delay for the jQuery script:
<script type="text/javascript">
window.setTimeout(function(){
alert($('.link:last').attr("href"));
}, 3000);
</script>
This sets a 3-second delay. Thank you for your answers!
Upvotes: 1
Views: 157
Reputation: 207919
Should be as easy as $('.link:last').attr('href')
alert($('.link:last').attr('href'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="slider">
<div id="slide1" class="slides">
<a href="items/show/1" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide2" class="slides">
<a href="items/show/2" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide3" class="slides">
<a href="items/show/3" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide4" class="slides">
<a href="items/show/4" class="link">
<h2>Date</h2>
<h3>Title</h3>
</a>
<div id="slide5" class="slides">
<a href="items/show/5" class="link"> <-- trying to get this href value
<h2>Date</h2>
<h3>Title</h3>
</a>
</div>
Upvotes: 0
Reputation: 241038
You need to select the last .slides
element. You could use:
var latestUrl = $('#slider .slides:last').find('a').attr("href");
console.log(latestUrl);
Alternatively, this would work too:
var latestUrl = $('a', '#slider .slides:last').attr("href");
console.log(latestUrl);
While using $('.link:last').attr('href')
may work given the HTML you provided, it wouldn't work if there was a .link
element outside of #slider
. In addition, it doesn't guarantee that it will be in the last .slides
element.
Upvotes: 0