Example:
<ul id="nav1">
<li><a href="page1.html">Page 1</a></li>
<li class="active"><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
</ul>
In this example im currently on Page 2, on Page 2 I want to place a Next Page
button with an url to Page 3.
How do I get the href
of Page 3 (with JavaScript)?
If you can use jQuery
$('.active').next('li').find('a').attr('href'); // page3.html
otherwise in plain javascript (example fiddle: http://jsfiddle.net/gGRcX/2/ )
var ul = document.getElementsById('nav1'),
link = ul.querySelector('li.active + li a');
if (link) { /* in case there's no "active" class
* (or if it's applied on last li element)
*/
console.log(link.href) // page3.html
}
querySelectorAll
works on every modern browser and on IE8+
$('#nav1 .active + li > a').attr('href');
CSS3 FTW :)
Edit: might even be CSS 2.x, too lazy to check.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.