2010 24 Mar
After the jQuery’s quick introduction of the last article, we’ll go more into details; in this article we’ll explore the selectors available to access DOM objects.
On top of standard CSS selectors jQuery introduces some custom selectors that make your code even simpler and easier to read. jQuery makes it easy to select elements you need using CSS selectors.
jQuery’s selectors allow the developers to quickly select all elements or groups of element of a given tag name, attribute name or their contents and allow you to manipulate them as a group or a single node.
The simplest way to select a DOM object is using the $() construct which takes as parameter any CSS selector expression.
Selector’s can be by tag name and its jQuery syntax is $(‘div), this syntax applies for all div tags in the document. And it can be by ID written as $(’#textId’) and selects element with Id = textId, and the third type of selection is by class written as $(‘.myclass’) to select all elements with the class myclass.
To get the full list of CSS selectors check the CSS selector list.
As you know, jQuery is a JavaScript library that you can include in any web page including any simple HTML page, so let’s try this simple example.
<html>
<head runat="server">
<title>jQuery Sample 1</title>
<script
src="jquery-1.4.1.js"
type="text/javascript"></script>
<script
type="text/javascript">
$(document).ready(
function() {
$('#myDiv1').hide();
}
);
function ShowDiv1() {
$('#myDiv1').show();
}
</script>
</head>
<body>
<div
id="myDiv1"
style="border: line
2px red;
background-color: Yellow; width:400px; height:400px;">
This is a testing div 1.
</div>
<div
style="border: line
2px Lime;
width:75px;
background-color: Fuchsia;" onclick="ShowDiv1();">
Show Div 1
</div>
</body>
</html>
In this example we’ve included the jquery-1.4.1.js script file to be able to call jQuery functions.
Starting by interpreting the body tag, we have 2 DIVs, the first is myDiv1 which just contains a text, and the second is used as a button, it calls ShowDiv1() java script function when the user clicks on it.
The ShowDiv1() function will select the myDiv1 div by id $('#myDiv1') and change its visibility to visible.
The example contains also a jQuery handler which runs when the document is ready, $(document).ready the contained function will run when the document loading is finished, but it doesn’t wait until the load of photos or other plug ins. The function will hide the myDiv1.
Thank you.



