0

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");
          });
nicael
  • 18,550
  • 13
  • 57
  • 90
Nate S.
  • 63
  • 8

2 Answers2

4

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 :)

nicael
  • 18,550
  • 13
  • 57
  • 90
  • Thank you! Any suggestions as to why the last bit does not work - cannot change the background color of the navbar-toggle button using the method described? Or, do you need more code for that one? – Nate S. Jul 26 '16 at 16:38
  • @Nate Try removing space? – nicael Jul 26 '16 at 16:39
  • Doesn't seem to work. Here is my jsfiddle if that helps: https://jsfiddle.net/m9m9q8mo/2/ – Nate S. Jul 26 '16 at 17:48
  • @Nate Anyway, that's a separate problem. You could ask another question. – nicael Jul 26 '16 at 17:53
1

As seen in this answer, you can select elements (e.g. named "navbar") that contain a specific class ("navbar-inverse") with "navbar.navbar-inverse". If you add a whitespace between those two, it basically means

Select all elements that have the class navbar-inverse and are children of the navbar

Cheers

Community
  • 1
  • 1
The M
  • 11
  • 4
  • The answer link was very helpful, thanks! Marking nicael's correct, though, just for succinctness. – Nate S. Jul 26 '16 at 16:39