Joshua Rajandiran Joshua Rajandiran - 2 months ago 6
CSS Question

How to add class to a html file loaded via jquery?

I've included my header & footer at separate html files using

.load()
from jQuery. My jQuery code is below:

$(function(){
$("#header").load("page-component/header.html");
$("#footer").load("page-component/footer.html");
});


Right now, as I navigate to another page, I want to add an
active
class to one of my header/footer links but I can't seem to achieve that. Anyone can help me?

I've tried something like this but it didn't work:

$(document).ready(function(){
jQuery('#menu-about').addClass('active');
});

Answer

Use complete callback of jQuery.load method.

.load( url [, data ] [, complete ] )

When you are invoking addClass method for element, element does not exist in DOM, callback function is invoked when external file is loaded in specified element

$(function() {
  $("#header").load("page-component/header.html", function() {
    jQuery('#menu-about').addClass('active');
  });
  $("#footer").load("page-component/footer.html", function() {
    jQuery('#menu-about').addClass('active');
  });
});