I'd like to display the ID of the active link in my navbar through an alert, but I'm not sure how to do this with my current Bootstrap 3 classes.
I was thinking of something like
alert( $('li').hasClass( "active" ).attr('id') );
but sadly that doesn't work.
Bootply
HTML:
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li class = "active"><a id = "tab1" href = "#" >Link1</a></li>
<li><a id="tab2" href = "#">Link2</a></li>
<li><a id = "tab3" href = "#" >Link3</a></li>
</ul><!-- END: "collapse navbar-collapse navHeaderCollapse" -->
</div><!-- END: "container" -->
</div><!-- END: "container" -->
</div><!-- END: "navbar navbar-inverse navbar-fixed-top" -->
I'd like to display the ID of the active link in my navbar through an alert, but I'm not sure how to do this with my current Bootstrap 3 classes.
I was thinking of something like
alert( $('li').hasClass( "active" ).attr('id') );
but sadly that doesn't work.
Bootply
HTML:
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class="nav navbar-nav navbar-right">
<li class = "active"><a id = "tab1" href = "#" >Link1</a></li>
<li><a id="tab2" href = "#">Link2</a></li>
<li><a id = "tab3" href = "#" >Link3</a></li>
</ul><!-- END: "collapse navbar-collapse navHeaderCollapse" -->
</div><!-- END: "container" -->
</div><!-- END: "container" -->
</div><!-- END: "navbar navbar-inverse navbar-fixed-top" -->
Share
Improve this question
asked Aug 13, 2014 at 0:02
michaelmichael
1676 silver badges23 bronze badges
2 Answers
Reset to default 5You need to find the child of the li
not the li
itself, also why not use the class in the selector instead of using hasClass
:
alert($('li.active a').attr('id'));
See Demo
Try this
$(function(){
alert( $('li.active a').prop('id') );
});