Nate S. Nate S. - 4 months ago 11
Javascript Question

$(".navbar.navbar-inverse").click() works but $(".navbar .navbar-inverse").click() does not?

I'm still learning the ropes of web design, and I am having trouble understanding how a couple of things work...

I created a function to toggle the navbar header background color, and I'm finding the following to be true but unsure why:

Works:

$(".navbar.navbar-inverse".click(function() {
$(this).toggleClass("highlight");
});


Does not work (space btw navbar and navbar-inverse):

$(".navbar .navbar-inverse".click(function() {
$(this).toggleClass("highlight");
});


Similarly, if I apply this function to the navbar-toggle, the opposite is true:

Works (space btw navbar and navbar-toggle):

$(".navbar .navbar-toggle").click(function() {
$(".navbar-inverse").toggleClass("highlight");
});


Does not work:

$(".navbar.navbar-toggle").click(function() {
$(".navbar-inverse").toggleClass("highlight");
});


Bonus...

Cannot change navbar-toggle background using this approach:

Does not work:

$(".navbar .navbar-toggle").click(function() {
$(this).toggleClass("highlight");
});

Answer

The first one refers an element with classes navbar and navbar-toggle, the second one refers .navbar-toggle which is a descendant of .navbar. That's what putting a space does :)