4

How can I change a CSS class of an HTML element in response to a changing page using PHP?

I already got the solution exactly like in this but this solution is for Javascript.

Basically, I want to add additional class when a certain IF condition is met. This is my code.

<li <?php if ($selected == "profile") echo 'class="active"'; ?> class="dropdown">
<a href="">Profile</a>
</li>

From my code, you can see that the <li> already got a class in it. So, when I echo another class in IF condition, it completely change to the class in IF condition.

What I need is an extra class, not different class. How can I do that?

1
  • 1
    class="dropdown <?php if ($selected == "profile") echo 'active'; ?>" Commented Sep 11, 2014 at 11:26

3 Answers 3

15

Just move it?

<li class="dropdown<?php if ($selected == "profile") echo ' active'; ?>">

This results in class="dropdown active", which is perfectly fine in HTML - you can have multiple space-separated classes on an element. All CSS rules targeting either of the two will be applied, and you can even combine them to require both:

li.active.dropdown {
  /* Underline active dropdown elements */
  text-decoration:underline;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, that's it! I just need to declare the condition in the class. Thanks!
3
 <li class="dropdown <?php if ($selected == "profile") echo 'active'; ?>">
    <a href="">Profile</a>
 </li>

try this

Comments

2

You can try this :

<li class="<?php if ($selected == "profile") echo 'active'; ?> OTHER CONDITION HERE ">
    <a href="">Profile</a>
</li>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.