Skip to content Skip to sidebar Skip to footer

Get The Name Of The Nav-item On Which It Was Clicked

I have a navbar designed in Bootstrap,I want to get the name of the nav-item on which it was clicked. I can set it to active currently but unable to retrieve the name of the nav-i

Solution 1:

$(this) is the li object, you want to use $(this).text() like this

   $('ul.navbar-nav > li').click(function (e) {
        e.preventDefault();
        var getItem = $(this).text();
        $('ul.navbar-nav > li').removeClass('active');
        $(this).addClass('active');
        $(".navbar-brand").after(" <ul class=\"navbar-nav\"><li class=\"nav-item active\"> <a class=\"nav-link\" href=\"#\">" + getItem + "<span class=\"sr-only\">(current)<\/span><\/a> <\/li><\/ul> ");
        $('.navbar-toggler').click();
    });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="collapse animated fadeInLeft"id="navbarNav"><ulclass="navbar-nav"><liclass="nav-item active"><aclass="nav-link"href="#">Home <spanclass="sr-only">(current)</span></a></li><liclass="nav-item"><aclass="nav-link"href="#">Features</a></li><liclass="nav-item"><aclass="nav-link"href="#">Pricing</a></li><liclass="nav-item"><aclass="nav-link disabled"href="#">Disabled</a></li></ul></div><divclass="navbar-brand"></div>

Solution 2:

You need to specify what you want to get from the this, use $(this).text() to get innerText, or $(this).html() to get innerHtml.

Post a Comment for "Get The Name Of The Nav-item On Which It Was Clicked"