Friday, April 29, 2011

Apply Multiple CSS classes on an HTML element (jQuery addClass)

Given this HTML:

<html>
<head>
  <style type="text/css">
    tr.Class1
    {
      background-color: Blue;
    }
    .Class2
    {
      background-color: Red;
    }
  </style>
</head>
<body>
  <table>
    <tr id="tr1">
      <td>Row 1</td>
    </tr>
    <tr id="tr2">
      <td>Row 2</td>
    </tr>
  </table>
</body>
</html>

Below is the script secion. What will happen when I click on the first row? Will it remain blue, or will it turn red? If it will remain blue, how do I get it to turn red instead WITHOUT removing the Class1 class from the row (so I can remove the Class2 class later and the row will return to its original color of blue)?

<script type="text/javascript" language="javascript">

  $(document).ready(function() {
    $("#tr1").addClass("Class1");

    $("tr").click(function() {
      /* clicked tr's should use the Class2 class to indicate selection, but only one should be selected at a time */

      $(".Class2").removeClass("Class2");
      $(this).addClass("Class2");
    });
  });

</script>

Edit I should say - I tried this, and it's not working as expected (in either FireFox or IE). What is going on?

From stackoverflow
  • It should turn red...that's why it's called cascading style sheets...new additions to the properties override older ones.

    Brandon Montgomery : I know, but I'm not getting that behavior.
  • Mozilla says here:

    If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

    But this isn't the behavior I'm getting.

  • try this:

     $("tr").click(function() {
      /* clicked tr's should use the Class2 class to indicate selection, but only one  should be selected at a time */
    
      $(".Class2").removeClass("Class2");
      $(this).toggleClass("Class1");
      $(this).addClass("Class2");
      $(this).toggleClass("Class1");
    });
    

    I don't know if it will work but maybe it will give you more into the problem.

  • Figured it out. I put my example up a little incorrectly. The CSS actually looked like:

    tr.Class1
    {
      background-color: Blue;
    }
    .Class2
    {
      background-color: Red;
    }
    

    Therefore, the most specific rule applies, just like Mozilla told me here:

    If the same property is declared in both rules, the conflict is resolved first through specificity, then according to the order of the CSS declarations. The order of classes in the class attribute is not relevant.

0 comments:

Post a Comment