Reputation: 5428
I'm trying to add a class to a pre-existing element, and I am trying the simplest of code. Anyone have any idea why the two logs would return the exact same element?
console.log($('.btn-group.archive'));
$('.btn-group.archive').addClass('open');
console.log($('.btn-group.archive'));
Might be worth mentioning that I'm using Twitter Bootstrap's dropdown menu, so I don't know if there is something messing with it from there.
They return:
<div class="btn-group archive">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Select
</a>
<ul class="dropdown-menu"><!-- dropdown menu links -->
<li><a href="#">Item #1</a></li>
<li><a href="#">Item #2</a></li>
</ul>
</div>
Where <div class="btn-group archive">
should be <div class="btn-group archive open">
.
The console is logging correctly, but the class won't add.
Upvotes: 0
Views: 230
Reputation: 47986
So I think this is just an issue of timing and that the console.log
command is throwing you off - but the commands do work and do occur in the order that you specify.
Take this example - Live Demo
<div id="foo"></div>
$(function(){
console.log($("#foo"));
setTimeout(function(){
$("#foo").addClass("bar");
console.log($("#foo"));
},40);
});
Outputs -
[<div id="foo"></div>]
[<div id="foo" class="bar"></div>]
Any interval smaller than 40 milliseconds yeilds the same output for both calls to console.log
- but that might vary from machine to machine and browser to browser.
I'm not sure if you are familiar with concept of buffering output as opposed to flushing all output as it comes... but this behavior can be seen in many different languages. I'm no expert on JavaScript so I'm not 100% sure that this is whats going on (outputs being buffered)...
Upvotes: 1