jQuery css()

Posted: September 3rd, 2010 | Author: | Filed under: AJAX, JavaScript, jQuery | No Comments »

I am the process of migrating a code base from Prototype + old-school JS to jQuery (the new mayor of Awesome Town), and ran across some code that was replacing some (but not all) styles of an element. This led me to jQuery’s css() method, one of the many handy CSS-related features in jQuery.. As I often do when tinkering with a new language, library, framework or feature I like to whip up a code sample. With this example I was able to see that the css() method adds css to an element without replacing other css attributes. A working example can be found here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<html>
<head>
	<title>styles</title>
	<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
	<script type="text/javascript">
	function modColor(){
		jQuery("#awesometown").css
			({
				'color':'red'
			});
	}
	function modStyle(){
		jQuery("#awesometown").css
			({
				'text-decoration':'underline'
			});				
	}
	function modVis(){
		jQuery("#awesometown").css
			({
				'display':'none'
			});
	}
	function modSize(){
		jQuery("#awesometown").css
			({
				'color':'black',
				'text-decoration':'none',
				'display':''
			});
	}
	</script>
</head>
<body>
	<h1 id="awesometown">I Am An H1 Tag On A Page With No Meaningful Content</h1>
	<em>sung to the tune of "Horse With No Name"</em>
	<hr />
	<a href="javascript:modColor();">red,</a> 
	<a href="javascript:modStyle();">underlined,</a> 
	<a href="javascript:modVis();">gone,</a> 
	<a href="javascript:modSize();">reset</a>
</body>
</html>

UPDATE

Here is another code snippet. This replaces five lines of code with one.

1
2
3
4
5
6
7
8
9
// the old code
$('XYZ').select('table.thisIsAClassname').each( 
    function (e) {
        e.style.display = 'none';
    }
);
 
// the new code
jQuery(".thisIsAClassname").css("display", "none");


Leave a Reply