Change #id background-color in PHP


Keywords:php 


Question: 

I change body background-color in PHP like this.

echo '<body style="background-color:orange">';

But how do i change an specific element background-color similar way in PHP? set m01 background to "black" if the passed variable mymonth gets value "1"

i have 12 elements with id from m01 to m12 like this for each month

<span id="m01" class="badge"><a href="">january</a></span>

1 Answer: 

Your first code sample doesn't really change the style but it declares it when you create the element.

You probably want to set the style when you create your element. Following code will set background color of created element to black if mymonth is 1, else it will be orange.

echo "<span id='m01' class='badge' style='background-color: ".(mymonth === 1 ? "black" : "orange")."'><a href=''>january</a></span>";

Changing styles however is not possible to do in PHP (nicely). There is probably some workaround I am not aware of, but Javascript is there for this. The following (a bit ugly and hacky) code changes color of month with id of mymonth variable to black:

echo '
<script>
document.getElementById("m'.(mymonth < 10 ? "0" : "").mymonth.'").style.background-color = "black";
</script>';