You old code;
$(window).load(function() {
// loops thoght each li
$('#demo3 > li').each(function(i){
// for each li we loop throguh, it creates a new jQuery object of all ('#demo3 > li') - wrong!
if($('#demo3 > li').hasClass('open')) {
// then adds class to the original loop's this (which is the current li element) - corrent.
$(this).addClass('active');
}
});
});
Change it to;
$(window).load(function() {
$('#demo3 > li').each(function(index, el){
if($(this).hasClass('open')){
$(this).addClass('active');
}
});
});
You used $(this) when trying to add class but didn't when checking if it had the class initially. So on your line where you check to see if it has the open class, you are actually creating a new jQuery object which will be an array of #demo3 li
's, and not the current li
you are iterating over.
As you can see I've added in the 2 params to the each function. index
being the current index of the itteration, el
being the current html element (not a jQuery object). You could replace $(this)
with $(el)
in this example.
But all in all, what you can do is only select those li's which have the 'open' class, and then just add 'active' to all of them;
$(window).load(function() {
$('#demo3 > li.open').addClass('active');
});