Where are we at?
In the first part of this tutorial, we downloaded and configured jQuery. In the second part we took a look at some basic event handling, unobtrusive JavaScript and very simple selectors. In this and the next installment, we will take a much more detailed look at selectors and see how they help us select just about any element in the associated html.
As mentioned in previous installments, jQuery and CSS are intimately related. The selector syntax used by jQuery is basically CSS selector syntax plus a little extra. So, for those of you who are not familiar with CSS, here is a quick overview of the basics used in the context of jQuery:
To select any html element in the doc, you just specify the element’s tag:
$(“input”)
Will return ALL of the inputs found in the entire document as a wrapped set. A wrapped set is simply the results of the selector as a collection. You can do fun things with this collection, like iterate over it. For example, to display an alert with the id of every div in your html file, you would use:
$(“div”).each(function(n) { alert(this.id);} );
For now, don’t worry about the “each” function. We’ll come back to that later.
Now, just being able to select all of an element isn’t exactly something to write home about. Often, you want to select things at a much more granular level. For example, to get all inputs contained within divs, you could use the following selector
$(“div input”)
Now, look at this in context of the following HTML:
When we run this selector against this html, we should get a wrapped set containing only inputs with id button1 and button2. There are a couple of interesting things to notice here:
We found the inputs even though they were within a span within the div. That is because the syntax $(“E1 E2?) returns the wrapped set containing any occurrence of E2 contained anywhere within E1. So…
While matching elements and their children is kind of cool, it’s not particularly useful. To make it more useful, we need to be more specific. i.e. “Get me the div named ‘mydiv’”. This is also pretty straightforward. All we need to do is borrow the attribute selector media from CSS. So, to match any input of type button, and ONLY of type button, we could use:
$(“input[type='button']“)
Note that we used single quotes inside the double quotes. You could leave off the single quotes in the above example, but fun little things like $(“input[value=my value]“) won’t get you what you want. So, you probably want the quotes. It enhances clarity as well. You can also just test for general existence of an attribute. For example:
$(“img[alt]“).each(function(n) { alert(this.alt);} );
Will produce a message box for each image with an alt text attribute. The general format to select based on attribute existence is
$(“Element[Attribute]“).
To select based on an attribute value the general format is:
$(“Element[Attribute=Value]“)
If you need to check for more than one attribute value, you can chain them together:
$(“input[value='new value'][type='button']“)
This will only return input buttons named button one, with a type attribute of button. Note that the above syntax is “and” type functionality. For “or” type functionality, you separate the entire selector by commas. So to select a button with a value of “my value” of type button, or a hidden input with a value of ‘secret’ of type hidden, you could use the following:
$(“input[value='my value'][type='button'], input[value='secret'][type='hidden']“)
jQuery selectors are amazingly versatile and we are only scratching the surface. You can use other operators besides equals. Valid operators include != and multiple string matching operations, as detailed below.
Some additional and very useful operators on attributes include:
Not Equals: Select elements where Element[Attribute] does not equal a value:
$(“input[value!='abc']“)
This returns all inputs other than ones with a value of abc.
Starts With: This is used to select elements where the attribute starts with the specified string.
For example:
$(“input[value^='abc']“)
This will return all inputs starting with ‘abc’. You could use this to return all buttons that start with a certain prefix: i.e.
$(“input[type='button'][id^='My']“)
This selector will return the set of buttons having ids that begin with ‘My’.
Ends With: This is used to select elements with an attribute value ending with the provided string.
For example:
$(“input[value$='xyz']“)
This will return all inputs ending with ‘xyz’. You could use this to return all text fields with values ending in ‘ing’ i.e.
$(“input[type=text'][id$='ing']“)
Contains: This is used to select elements with an attribute value containing the provided string
For example:
$(“input [value*='pqr']“)
This will return all inputs containing the string ‘pqr’. You could use this as an alternate way to to return all buttons starting with ‘My’
$(“input [type=text'][id*='My']“)
So as a quick review, the table shown below lists all the selector operations we’ve looked at so far:
Match Element(s) with a tag of elementMatch Element w/another tag as a descendentMatch where an attribute is presentMatch where attribute equals a valueMatch where attribute doesn’t equals valueMatch where attribute starts w/valueMatch where attribute ends w/valueMatch where attribute contains valueWe covered a lot of ground in this installment, but we are just getting started with selectors. In the next installment we will take a look at more selector options as well as dig deeper into each type. Selectors are the heart of jQuery, so they are well worth understanding. Play with these in your code and prepare to learn even more.
Larry Schoeneman is a software developer with over 20 years of experience, focused on Microsoft products and technologies as well as utilizing agile methodologies to build better software.
If you found this post useful you may also want to check these out:
Get Rolling With jQuery – Part 2A Quick Introduction to JQuery – Part 1HTML Form Tutorial, Part IStyling Disabled Buttons / Disabled Text Boxes in CSSHTML Form Tutorial, Part IIRolling with Razor in MVC v3 Preview – Part 3
No comments:
Post a Comment