Piotr
Piotr

Reputation: 53

Can I add/remove class on element loaded by load() function?

I have a navbar with class called "active" with some CSS styling. The navbar is used on a number of subpages so I figured out that instead of repeating the code on all the subpages I will load navbar with load() function.

The problem is that with the content loaded by the load() function I cannot remove the class using removeClass(). The navbar is loaded, I can see the tags in inspector, and all seems to be OK. The code is working if I put the navbar manually in the HTML.

I've tried to move the script tag that deletes the class after the CDN script, but it does not help (the idea was to remove class on the fully loaded page). What am I missing?

I'm using the following code to load the navbar:

$(function(){
  $("#includeNavbar").load("../partials/navbar.html"); 
});

Then I put a tag in HTML:

<div id="includeNavbar"></div>  

Then I use <script> tag in the HTML, but below code does not remove class:

<script>
  $("li").removeClass("active");
  $("li").eq(1).addClass("active");             
</script>

Upvotes: 2

Views: 421

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337620

The issue is where you're calling removeClass() and addClass() from. You need to do it in the callback of the load(), to ensure that the content exists in the DOM when you execute those calls:

$(function(){
  $("#includeNavbar").load("../partials/navbar.html", function() {
    $("li").removeClass("active").eq(1).addClass("active");
  }); 
});

Upvotes: 1

Related Questions