Reputation: 859
I want to extract each anchor tag link out of a menu I've set up for an online course
The ul id is #sidebar
the li's in the sidebar are in the right chapter orders, so I would like to find which chapter page the user is on and then grab the previous chapter and the next chapter, to pass to some other anchor tags at the bottom of each chapter.
This is how far I've gotten.
for(var i = 0; i < $("#sidebar ul li").size(); i++) {
console.log('chapter '+i+' = ',$("#sidebar ul li").get(i))
}
This returns each li element, so how do I now grab the a href value inside each li returned?
I tried putting .a on the end , didn't work. Couldn't find much in google either.
Thanks
Upvotes: 0
Views: 1100
Reputation: 859
Hey guys thanks for your prompt answers,
I ended up getting this to do what I want with a bit of fiddling around.
This is what I come up with...
$(document).ready(function(){
var previouschap;
var nextchap;
var chapter ="<?php echo (isset($_GET['chapter'])) ? $_GET['chapter'] : 'No Chapter'; ?>";
for(var i = 0; i < $("#sidebar li").size(); i++) {
liresult = $($("#sidebar li a").get(i)).attr('href');
if(liresult == './index.php?chapter='+chapter)
{
previouschap = $($("#sidebar li a").get(i-1)).attr('href');
nextchap = $($("#sidebar li a").get(i+1)).attr('href');
$('#previous-chapter').attr('href', previouschap);
$('#next-chapter').attr('href', nextchap);
break;
}
}
});
Upvotes: 0
Reputation: 74738
Try this one: in fiddle here
var $sidelist = $("#sidebar ul li").size();
for (var i = 0; i < $sidelist; i++) {
console.log('chapter ' + Math.floor(i + 1) + ' = ', $("#sidebar ul li").find('a').eq(i).attr('href'));
}
Output of above is:
//this is the output of for loop:
chapter 1 = #chaper-1
chapter 2 = #chaper-2
chapter 3 = #chaper-3
or with $.each()
:
var $sidelist = $("#sidebar ul li");
$.each($sidelist, function(i, v){
console.log('chapter '+Math.floor(i + 1)+' = ' + $(this).find('a').attr('href'));
});
You have to do this Math.floor(i + 1)
to start the chapter with index 1 otherwise this will start at 0
.
Upvotes: 4
Reputation: 1559
From performance perspective, it's important to run selector just once, out of loop.
var links = $("#sidebar ul li a"); // equivalent to $("#sidebar ul li").find('a')
for(i = 0, length = links.length; i < length; ++i){
console.log('chapter '+ i + ' = ' + $(links[i]).attr('href'));
}
Upvotes: 2
Reputation: 1014
Make use of FIND (),
for(var i = 0; i < $("#sidebar ul li").size(); i++) {
console.log('chapter'+ i +' = ',$("#sidebar ul li").find('a').eq(i).attr('href'));
}
Upvotes: 1