Mohamad Fazel Hesari
Mohamad Fazel Hesari

Reputation: 116

if an element has a particular class do sth on another element

I have a question with .hasClass method in jquery.

For example I want my menu button color to become red when my div element with .show class exists.

So I have written this code for explain this solution

 if ($(".navbar-collapse").hasClass("show"))
    $(".menuIcon").css("color", "red");

but this code didn't work when I tested... how can I fix this problem?

Upvotes: 0

Views: 55

Answers (4)

Ehsan
Ehsan

Reputation: 12969

Only with css:

.navbar-collapse.show {
    color:red!important; 
}

Upvotes: 0

Lajos Arpad
Lajos Arpad

Reputation: 77063

Your code looks to be ok, but the behavior you are experiencing can be due to one or more of the following:

  • you might be missing to include jquery (include it using the script tag if so)
  • you might have an error in your console (fix it if so)
  • your code might be executed before your tag having the show class is created or before the show class is being added to the tag
  • the show class might be added to another tag
  • you might want to override background-color instead of color
  • another javascript might override your desired behavior

To get a more exact response, you need to ask a more exact question.

Upvotes: 0

samo0ha
samo0ha

Reputation: 3796

your code is totally correct , and it should works . just make sure of
1- your jquery library is exists and loaded coreectly .
2- the styles associated with your code is exists in the page and true
3- contain your code inside $(document).ready(function(){ }); to ensure the styles are loaded before the code excuted .

$(document).ready(function(){
     if ($(".navbar-collapse").hasClass("show")){
         $(".menuIcon").css("color", "red");
      }
});

Upvotes: 1

Nick
Nick

Reputation: 417

Try this:

$(".navbar-collapse.show").find(".menuIcon").css("color", "red");

You can associate it with the event that changes the menu.

Upvotes: 0

Related Questions