Jquery notes–how to set a css property on a element

by Bojan Vrhovnik 7. February 2011 19:23

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 Smile).

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?

image

p.s. We could check, if tr is in table header (select query must be more specific)

$('#contactContainer tbody tr:even').addClass('myCssClass');

Tags: , ,

JQuery | Learning | Notes

Comments (1) -

Klemen Slovenia
2/8/2011 1:17:50 PM #

You might want to consider using the shorthand version of the `ready` event handler:

$(function() { ... });

Passing a function directly into jQuery assumes it is a document.ready handler.

Reply

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading






About me

I love stretching my mind and having a blast in development, since it is a hobby and my profession. More about me on http://www.vrhovnik.net. I do have like to experiment with various toys, project, so i'm in preparation of my own playground, which will be avaliable on http://projects.preliator.net/bojanv.

Month List

Widget Twitter not found.

Root element is missing.X