Sunday, October 9, 2011

JQUERY Selectors and Filters Basics


As the name implies JQUERY Selectors and Filters do as they are supposed to do. They select content from document so that the content can be manipulated using other functions may be with JQUERY function or other JavaScript functions.

In a brief the JQUERY selector returns an array of objects that matched the selection criterion and the JQUERY filters are there to refine the selection the selector returns.

The content that the JQUERY objects return is not DOM elements but JQUERY elements wrapped by JQUERY objects so then they can be further processed using lots of predefined JQUERY functions.


The most important features of using JQUERY selectors and filters is that they are build as CSS syntax, that makes then easily understandable as CSS is most commonly used and everybody is familiar with it.  Here are some selectors that directly use some CSS part.

Such as The tagname selector finds all the elements within the tagname, #identifier selector finds elements with ID of identifier, .className selector finds the elements that have the class attribute with the value of className, tag.className finds the tag elements that have a class with the value of className, tag#id.className finds the elements of specific tag that has a ID value of id and a class attribute with class value of className. And * finds all the elements on the page.

JQUERY vs DOM: an example

Here is an example that helps to show that how easy JQUEY makes to find elements. First just consider the following HTML file:

<html>
<head>
<title>My JQUERY Example</title>
</head>
<body>
<div id = “container”>
Here goes some list of element:
<ul id=”ullist”>
<li class=”first”>Element 1</li>
<li class=”first”>Element 2</li>
<li class=”second”>Element 3</li>
<li class=”third”>Element 4</li>
<li class=”third”>Element 5</li>
<ul>
<p>a test paragraph 1</p>
<p>a test paragraph 2</p>
<p>a test paragraph 3</p>
</div>
<body>
</html>
This is a very simple HTML file, now if we want process it further then we have find the content first.

Now the code for finding all elements with “ullist” tag in DOM is as follow:
document.getElementById(“ullist”);

In JQUERY the code will be:
$(“#ullist”);

To find all <p> tags
In DOM : document.getElementByTagName(“p”);
In JQUERY: $(“p”);

Now if we want to get all the class “first” form all the <li> tags then it will be more complex in DOM. In DOM first all the <li> tag needs to find out using getElementBYTagName, then with a for loop have to compare all the class with “first” to find out the which class value is “first”.

On the other hand it is very easy in JQUERY.
In JQUERY the code will be:
$(“li.first”);

0 comments:

Post a Comment