Reputation: 35
I put my navbar in a separated file to avoid duplicate the HTML code of this. So, I include my navbar with
$("#includeNavbar").load("/navbar.html");
But I want to edit the navbar to put an active tab (bootstrap). I would like to do something like it :
$(function() {
$("#includeNavbar").load("/navbar.html");
$("#includeNavbar>li").each(function(){
if($(this).text() == "CV"){
$(this).addClass("active");
}
});
});
But it doesn't work... Some help please...
Upvotes: 0
Views: 72
Reputation: 2828
Put your code in the callback like this :
$("#includeNavbar").load("/navbar.html",function(){
$("#includeNavbar>li").each(function(){
if($(this).text() == "CV"){
$(this).addClass("active");
}
});
});
This will be called after elements loading
Upvotes: 0
Reputation: 59272
You've to do it in complete callback since it is loaded asynchronously. You can use filter to..
$("#includeNavbar").load("/navbar.html", function() {
$(this).find('li').filter(function() {
return $(this).text() == "CV"
}).addClass("active");
});
Upvotes: 1
Reputation: 7328
In order to interact with the file, you must wait until it loads first. The JQuery.load function has a 2nd argument which is a callback function. The following utilizes that callback and should fire once the page is fully loaded:
$(function() {
$("#includeNavbar").load("/navbar.html", function() {
$("#includeNavbar>li").each(function(){
if($(this).text() == "CV"){
$(this).addClass("active");
}
});
});
});
Upvotes: 0
Reputation: 1821
Here's the code, try it:
$("#includeNavbar").load("/navbar.html", function(){
$("#includeNavbar li").each(function(){
if($(this).text() == "CV"){
$(this).addClass("active");
}
});
});
That's it.
Upvotes: 0