jQuery is a lightweight JavaScript library which allows you to create dynamic client-side effects with simple code. The code is very stripped back from typical JavaScript – the code for selecting elements and their descendents is more similar to CSS than DOM syntax. The logic behind the code is also similar to CSS. Like how CSS separates design from the HTML structure, jQuery separates the behavior. jQuery can be activated simply by linking to it as you would any other external JavaScript file.
To reference a jQuery function, you must supply a namespace. This can be written as ‘jQuery’, but is conventionally written as ‘$’. For example;
jQuery.trim(string);
// is the same as
$.trim(string);
Whole elements can be selected, including those with particular classes or IDs. The class and ID selectors are ‘.’ and ‘#’ respectively, the same as in CSS.
// select all paragraphs
$(“p”);
// select all paragraphs with the ‘main’ class
$(“p.main”);
// set the value of the element with the ID of ‘unique'
$(“#unique”).val(“testing”);
Adding and removing classes to tags can be done easily with the addClass() and removeClass() functions.
$(“a”).addClass(“primary-link”);
$(“a”).removeClass(“primary-link”);
You can test if an element has a class by using the hasClass() function.
if ( $(“p”).hasClass(“important”) )
…
Functions are also chainable to help with more complicated selection and tasks.
// add an “impressive” class to all paragraphs within the “parent” div
$(“div#parent”).add(“p”).addClass(“impressive”);
As you can see from these code examples, jQuery allows you to do a lot with very little code. It’s this simplification and separation from the main HTML structure that makes it so useful for web developers. Use of jQuery has risen dramatically since its launch in 2006, with big names like the BBC, MSNBC and Digg now using it prominently. This popularity should see it stick around for a while, and is a useful addition to any developer’s toolkit.
This entry was posted on Sunday, February 8th, 2009 at 11:51 am and is filed under Web development, JavaScript, jquery. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
Comments are closed.








