This is a tip I found in Jquery from novice to ninja. I’m not an css expert, but I’m eager to learn.
How do we set a property (attribute) on an element? Usually the answer would be, we use css. We create a rule, class and set the class with it. Fairly simple, but what if we want to set it dynamically? If we set an css class, then the simplest thing for manipulating its state, its javascript (or other scripting language
).
Ok, lets do this in jquery:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#contactContainer tr').css('background-color', '#dddddd');
});
</script>
This takes every row in table (in a div contactContainer) and set its background color to lightgray. Neat, a? What if we want to set a more css rules on a element? We can do this usual way: duplicate or triplicate line etc. Not so efficient, a?
Well, we can use so called object literal (we do have a similar concept in .NET).
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#contactContainer tr').css({
'background-color', '#dddddd',
'color','Red'
});
});
</script>
Well, this can be done even more efficient and beautiful. We can use addClass option. Usage is very simple.
$('#contactContainer tr:even').addClass('myCssClass');
And result?

p.s. We could check, if tr is in table header (select query must be more specific)
$('#contactContainer tbody tr:even').addClass('myCssClass');