0

So basically i would like to color the comments from users so it look clear and separate. The comments is coming from the database, the php codes will generate the comments in a HTML page. And i am using CSS and Jquery as well. I have tried but my codes don't work, any idea?

HTML/PHP:

    <? 
for($i=0;$i<mysql_num_rows($comment);++$i)
{
$row = mysql_fetch_array($comment);
?>  
        <div class = "comment">
        <p> <? echo $row['c_content']; ?>  by <? echo $row['c_name']; ?> </p>
        </div>
        <?}?>

CSS:

.comment
{
    background-color:#fff;     
}

.alt
{
    background-color:#ccc;
}

Jquery:

$(document).ready(function(){
$(".comment:odd").addClass('alt');
});

So as you can see, I want the "odd" comment class have color #CCC, and the even have #FFF... Please help

1
  • If you're generating the table with PHP and it's not going to be shifted around 'n' stuff, you could add "odd" and "even" classes in your loop in PHP. Commented Apr 28, 2012 at 4:01

1 Answer 1

2

No need to use jQuery here. Use CSS:

.comment:nth-child(even) {
    background-color: #fff;
}

.comment:nth-child(odd) {
    background-color: #ccc;
}

Unrelated, but worth noting is that unless you're using both associate and numerical keys to access your mysql result, you should get into the habit of using mysql_fetch_assoc() instead of mysql_fetch_array() or you are always using twice as much memory.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your time! But just in case if i would like to stick with jquery, what mistake i made>?
You could try adding !important to the .alt class or replacing the class instead of adding to it.
!important is icky stuff you should avoid unless you absolutely MUST use it. Just make it more specific; for example if these elements are divs, the CSS becomes div.alt which is more specific than just .comment. So-called "specificity wars" are also icky, but for an example like this, it's the right way to go!

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.