Reputation: 6541
I am trying to find the current page in a ul and create a link to the previous or next li
I have a top menu in the structure of:
<ul id=menu>
<li><a>Category A</a>
<ul>
<li><a>Sub Page 1</a></li>
<li><a>Sub Page 2</a></li>
<li><a>Sub Page 3</a></li>
</ul></li>
<li><a>Category B</a>
<ul>
<li><a>Sub Page 4</a></li>
<li><a>Sub Page 5</a></li>
</ul></li></ul>
The idea being if I am on page 4 the back button will take me to page 3, and the next will take me to page 5.
I can get my current filename with
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
And the list of my links with
document.getElementById('menu');
And I am guessing once I match the filename to the links, I can use some form of next() & previous(), but I am not clear on how to find my variable filename in the code, and then select the next element. And the elements are to be on the same level, so the next of page 3 goes to page 4, not page 4's parent category B.
I am not using jQuery, and would prefer a non jQuery code if that was possible.
Upvotes: 0
Views: 114
Reputation: 2289
Something like this should work
function currentPath() {
var url = window.location.pathname;
return url.substring(url.lastIndexOf('/')+1);
}
function getHrefForLi(li) {
return li.getElementsByTagName('a')[0].href.split('/').pop();
}
var lis = document.getElementById('menu').getElementsByTagName('li');
for (var i = 0, n = lis.length; i < n; i++) {
if (getHrefForLi(lis[i]) == currentPath()) {
var prev = i > 0 ? getHrefForLi(lis[i-1]) : null,
next = i < n - 1 ? getHrefForLi(lis[i+1]) : null;
break;
}
}
prev
and next
will be the value of the previous and next <a>
tags href
attribute values or null
if the active path is the first or last.
Upvotes: 1