michael
michael

Reputation: 167

How to get the ID of an active link

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" -->

Upvotes: 1

Views: 5157

Answers (2)

Vahid Moradi
Vahid Moradi

Reputation: 791

Try this

$(function(){
  alert( $('li.active a').prop('id') );
});

Upvotes: 0

Guy
Guy

Reputation: 11305

You 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

Upvotes: 5

Related Questions