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?

Community
  • 1
  • 1
user2781911
  • 79
  • 1
  • 2
  • 9

3 Answers3

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;
}
Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
3
 <li class="dropdown <?php if ($selected == "profile") echo 'active'; ?>">
    <a href="">Profile</a>
 </li>

try this

2

You can try this :

<li class="<?php if ($selected == "profile") echo 'active'; ?> OTHER CONDITION HERE ">
    <a href="">Profile</a>
</li>
web-tiki
  • 99,765
  • 32
  • 217
  • 249