Learning Curve…

JQuery selectors …

Posted on: October 17, 2011

JQuery selectors enable us to find one or more elements in your page’s document object model so we can apply all sorts of jQuery methods to these elements. Rather than inventing a new technique to find page elements, the designers of jQuery decided to use an existing CSS selector-based syntax:

1. The Universal Selector

The universal selector matches all elements in your page. To set the fontfamily of each element in a page to Arial, we can use this code:

$(‘*’).css(‘font-family’, ‘Arial’);

2. The ID Selector

This selector finds and retrieves an element by its id. For example, to set the CSS class for a button called Button1, we can use this code:


3.The Element Selector

This selector gets a reference to zero or more elements that match a specific tag name. For example, this code turns the text colour of all headings at level two to blue:

$(‘h2’).css(‘color’, ‘blue’);

4. The Class Selector

The class selector gets a reference to zero or more elements that match a specific class name.

Consider this HTML fragment:

<h1 class=”Highlight”>Heading 1</h1>

<h2>Heading 2</h2>

<p class=”Highlight”>First paragraph</p>

<p>Second paragraph</p>

Notice how two of the four elements have a CSS class called Highlight. The following jQuery code changes the background colour of the first heading and the first paragraph to red, leaving the other elements unmodified:

$(‘.Highlight’).css(‘background-color’, ‘red’);

5. Grouped and Combined Selectors

We can group and combine selectors. The following grouped selector changes the text colour of all h1 and h2 elements in your page:

$(‘h1, h2’).css(‘color’, ‘orange’);

With a combined selector, you can find specific elements that fall within some others. For example, the following jQuery touches just the paragraphs that fall within the MainContent element, leaving all other paragraphs alone:

$(‘#MainContent p’).css(‘border’, ‘1px solid red’);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Learning days (Calendar)

October 2011
« Sep   Nov »

Knowledge Bank (Archives)

I am on Twitter

Blog Stats

  • 571,090 hits

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 43 other followers

%d bloggers like this: