Search code examples
jqueryclassexternalnav

How to add a class to a nav ul li a using jQuery when the nav is in an external file?


I have a dashboard with a navigation on the left side. The navigation is declared on an external file named nav.html.

In every page I load the navigatoin using jQuery using this:

  <script>
     $(function () {
        $.get("nav.html", function (data) {
        $("nav").append(data);
        });
     });
  </script>

Now I try to add a class on the active a element and I didn't find a way...

Thanks very much for your help.


Solution

  • You didn't show the structure of nav.html, but I assume you do know which element should be active. One possible approach:

    $.get("nav.html", function(navHtml) {
      var $navHtml = $(navHtml);
      var $activeLink = $navHtml.find('a[href="' + getActiveLink() + '"]'); // for example
      $activeLink.addClass('active');
      $("nav").append($navHtml);
    });
    

    The point is creating a jQuery object wrapping an HTML element not yet attached to window.document - this element is created from parsing html file. You can process this object the same way you do the 'real ones' from DOM - in particular, find a specific element with .find() method, then add a specific class to that element with .addClass().