jQuery Selectors

Posted by Jeffye | 10:34 PM

jQuery Selectors

Use the excellent jQuery Selector Tester to experiment with the different selectors.
If you need more details and explanations, go http://api.jquery.com/category/selectors/
SelectorExampleSelects
*$("*")All elements
#id$("#lastname")The element with id="lastname"
.class$(".intro")All elements with class="intro"
.class,.class$(".intro,.demo")All elements with the class "intro" or "demo"
element$("p")All <p> elements
el1,el2,el3$("h1,div,p")All <h1>, <div> and <p> elements
   
:first$("p:first")The first <p> element
:last$("p:last")The last <p> element
:even$("tr:even")All even <tr> elements
:odd$("tr:odd")All odd <tr> elements
   
:first-child$("p:first-child")All <p> elements that are the first child of their parent
:first-of-type$("p:first-of-type")All <p> elements that are the first <p> element of their parent
:last-child$("p:last-child")All <p> elements that are the last child of their parent
:last-of-type$("p:last-of-type")All <p> elements that are the last <p> element of their parent
:nth-child(n)$("p:nth-child(2)")All <p> elements that are the 2nd child of their parent
:nth-last-child(n)$("p:nth-last-child(2)")All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n)$("p:nth-of-type(2)")All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n)$("p:nth-last-of-type(2)")All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child$("p:only-child")All <p> elements that are the only child of their parent
:only-of-type$("p:only-of-type")All <p> elements that are the only child, of its type, of their parent
   
parent > child$("div > p")All <p> elements that are a direct child of a <div> element
parent descendant$("div p")All <p> elements that are descendants of a <div> element
element + next$("div + p")The <p> element that are next to each <div> elements
element ~ siblings$("div ~ p")All <p> elements that are siblings of a <div> element
   
:eq(index)$("ul li:eq(3)")The fourth element in a list (index starts at 0)
:gt(no)$("ul li:gt(3)")List elements with an index greater than 3
:lt(no)$("ul li:lt(3)")List elements with an index less than 3
:not(selector)$("input:not(:empty)")All input elements that are not empty
   
:header$(":header")All header elements <h1>, <h2> ...
:animated$(":animated")All animated elements
:focus$(":focus")The element that currently has focus
:contains(text)$(":contains('Hello')")All elements which contains the text "Hello"
:has(selector)$("div:has(p)")All <div> elements that have a <p> element
:empty$(":empty")All elements that are empty
:parent$(":parent")All elements that are a parent of another element
:hidden$("p:hidden")All hidden <p> elements
:visible$("table:visible")All visible tables
:root$(":root")The document’s root element
:lang(language)$("p:lang(de)")All <p> elements with a lang attribute value starting with "de"
   
[attribute]$("[href]")All elements with a href attribute
[attribute=value]$("[href='default.htm']")All elements with a href attribute value equal to "default.htm"
[attribute!=value]$("[href!='default.htm']")All elements with a href attribute value not equal to "default.htm"
[attribute$=value]$("[href$='.jpg']")All elements with a href attribute value ending with ".jpg"
[attribute|=value]$("[hreflang|='en']")All elements with a hreflang attribute value starting with "en"
[attribute^=value]$("[name^='hello']")All elements with a name attribute value starting with "hello"
[attribute~=value]$("[name~='hello']")All elements with a name attribute value containing the word "hello"
[attribute*=value]$("[name*='hello']")All elements with a name attribute value containing the string "hello"
   
:input$(":input")All input elements
:text$(":text")All input elements with type="text"
:password$(":password")All input elements with type="password"
:radio$(":radio")All input elements with type="radio"
:checkbox$(":checkbox")All input elements with type="checkbox"
:submit$(":submit")All input elements with type="submit"
:reset$(":reset")All input elements with type="reset"
:button$(":button")All input elements with type="button"
:image$(":image")All input elements with type="image"
:file$(":file")All input elements with type="file"
:enabled$(":enabled")All enabled input elements
:disabled$(":disabled")All disabled input elements
:selected$(":selected")All selected input elements
:checked$(":checked")All checked input elements

If there is one bad thing about jQuery, it’s that the entry level is so amazingly low, that it tends to attract those who haven’t an ounce of JavaScript knowledge. Now, on one hand, this is fantastic. However, on the flip side, it also results in a smattering of, quite frankly, disgustingly bad code (some of which I wrote myself!).
But that’s okay; frighteningly poor code that would even make your grandmother gasp is a rite of passage. The key is to climb over the hill, and that’s what we’ll discuss in today’s tutorial.

1. Methods Return the jQuery Object

It’s important to remember that most methods will return the jQuery object. This is extremely helpful, and allows for the chaining functionality that we use so often.
  1. $someDiv  
  2.   .attr('class''someClass')  
  3.   .hide()  
  4.   .html('new stuff');  
Knowing that the jQuery object is always returned, we can use this to remove superfluous code at times. For example, consider the following code:
  1. var someDiv = $('#someDiv');  
  2. someDiv.hide();  
The reason why we “cache” the location of the someDiv element is to limit the number of times that we have to traverse the DOM for this element to once.
The code above is perfectly fine; however, you could just as easily combine the two lines into one, while achieving the same outcome.
  1. var someDiv = $('#someDiv').hide();  
This way, we still hide the someDiv element, but the method also, as we learned, returns the jQuery object — which is then referenced via the someDiv variable.

2. The Find Selector

As long as your selectors aren’t ridiculously poor, jQuery does a fantastic job of optimizing them as best as possible, and you generally don’t need to worry too much about them. However, with that said, there are a handful of improvements you can make that will slightly improve your script’s performance.
One such solution is to use the find() method, when possible. The key is stray away from forcing jQuery to use its Sizzle engine, if it’s not necessary. Certainly, there will be times when this isn’t possible — and that’s okay; but, if you don’t require the extra overhead, don’t go looking for it.
  1. // Fine in modern browsers, though Sizzle does begin "running"  
  2. $('#someDiv p.someClass').hide();  
  3.   
  4. // Better for all browsers, and Sizzle never inits.  
  5. $('#someDiv').find('p.someClass').hide();  
The latest modern browsers have support forQuerySelectorAll, which allows you to pass CSS-like selectors, without the need for jQuery. jQuery itself checks for this function as well.
However, older browsers, namely IE6/IE7, understandably don’t provide support. What this means is that these more complicated selectors trigger jQuery’s full Sizzle engine, which, though brilliant, does come along with a bit more overhead.
Sizzle is a brilliant mass of code that I may never understand. However, in a sentence, it first takes your selector and turns it into an “array” composed of each component of your selector.
  1. // Rough idea of how it works  
  2.  ['#someDiv, 'p'];  
It then, from right to left, begins deciphering each item with regular expressions. What this also means is that the right-most part of your selector should be as specific as possible — for instance, an id or tag name.
Bottom line, when possible:
  • Keep your selectors simple
  • Utilize the find() method. This way, rather than using Sizzle, we can continue using the browser’s native functions.
  • When using Sizzle, optimize the right-most part of your selector as much as possible.

Context Instead?

It’s also possible to add a context to your selectors, such as:
  1. $('.someElements''#someContainer').hide();  
This code directs jQuery to wrap a collection of all the elements with a class of someElements — that are children of someContainer — within jQuery. Using a context is a helpful way to limit DOM traversal, though, behind the scenes, jQuery is using the find method instead.
  1. $('#someContainer')  
  2.   .find('.someElements')  
  3.   .hide();  

Proof

  1. // HANDLE: $(expr, context)  
  2. // (which is just equivalent to: $(context).find(expr)  
  3. else {  
  4.    return jQuery( context ).find( selector );  
  5. }  

3. Don’t Abuse $(this)

Without knowing about the various DOM properties and functions, it can be easy to abuse the jQuery object needlessly. For instance:
  1. $('#someAnchor').click(function() {  
  2.     // Bleh  
  3.     alert( $(this).attr('id') );  
  4. });  
If our only need of the jQuery object is to access the anchor tag’s id attribute, this is wasteful. Better to stick with “raw” JavaScript.
  1. $('#someAnchor').click(function() {  
  2.     alert( this.id );  
  3. });  
Please note that there are three attributes that should always be accessed, via jQuery: “src,” “href,” and “style.” These attributes require the use of getAttribute in older versions of IE.

Proof

  1. // jQuery Source  
  2. var rspecialurl = /href|src|style/;  
  3. // ...   
  4. var special = rspecialurl.test( name );  
  5. // ...  
  6. var attr = !jQuery.support.hrefNormalized && notxml && special ?  
  7.     // Some attributes require a special call on IE  
  8.     elem.getAttribute( name, 2 ) :  
  9.     elem.getAttribute( name );  

Multiple jQuery Objects

Even worse is the process of repeatedly querying the DOM and creating multiple jQuery objects.
  1. $('#elem').hide();  
  2. $('#elem').html('bla');  
  3. $('#elem').otherStuff();  
Hopefully, you’re already aware of how inefficient this code is. If not, that’s okay; we’re all learning. The answer is to either implement chaining, or to “cache” the location of #elem.
  1. // This works better  
  2. $('#elem')  
  3.   .hide()  
  4.   .html('bla')  
  5.   .otherStuff();  
  6.   
  7. // Or this, if you prefer for some reason.  
  8. var elem = $('#elem');  
  9. elem.hide();  
  10. elem.html('bla');  
  11. elem.otherStuff();  

4. jQuery’s Shorthand Ready Method

Listening for when the document is ready to be manipulated is laughably simple with jQuery.
  1. $(document).ready(function() {  
  2.     // let's get up in heeya  
  3. });  
Though, it’s very possible that you might have come across a different, more confusing wrapping function.
  1. $(function() {  
  2.     // let's get up in heeya  
  3. });  
Though the latter is somewhat less readable, the two snippets above are identical. Don’t believe me? Just check the jQuery source.
  1. // HANDLE: $(function)  
  2. // Shortcut for document ready  
  3. if ( jQuery.isFunction( selector ) ) {  
  4.     return rootjQuery.ready( selector );  
  5. }  
rootjQuery is simply a reference to the root jQuery(document). When you pass a selector to the jQuery function, it’ll determine what type of selector you passed: string, tag, id, function, etc. If a function was passed, jQuery will then call its ready() method, and pass your anonymous function as the selector.

5. Keep your Code Safe

If developing code for distribution, it’s always important to compensate for any possible name clashing. What would happen if some script, imported after yours, also had a $ function? Bad stuff!
The answer is to either call jQuery’s noConflict(), or to store your code within a self-invoking anonymous function, and then pass jQuery to it.

Method 1: NoConflict

  1. var j = jQuery.noConflict();  
  2. // Now, instead of $, we use j.   
  3. j('#someDiv').hide();  
  4.   
  5. // The line below will reference some other library's $ function.  
  6. $('someDiv').style.display = 'none';  
Be careful with this method, and try not to use it when distributing your code. It would really confuse the user of your script! :)

Method 2: Passing jQuery

  1. (function($) {  
  2.     // Within this function, $ will always refer to jQuery  
  3. })(jQuery);  
The final parens at the bottom call the function automatically – function(){}(). However, when we call the function, we also pass jQuery, which is then represented by $.

Method 3: Passing $ via the Ready Method

  1. jQuery(document).ready(function($) {  
  2.  // $ refers to jQuery  
  3. });  
  4.   
  5. // $ is either undefined, or refers to some other library's function.  

6. Be Smart

Remember – jQuery is just JavaScript. Don’t assume that it has the capacity to compensate for your bad coding. :)
This means that, just as we must optimize things such as JavaScript for statements, the same is true for jQuery’s each method. And why wouldn’t we? It’s just a helper method, which then creates a forstatement behind the scenes.
  1. // jQuery's each method source  
  2.     each: function( object, callback, args ) {  
  3.         var name, i = 0,  
  4.             length = object.length,  
  5.             isObj = length === undefined || jQuery.isFunction(object);  
  6.   
  7.         if ( args ) {  
  8.             if ( isObj ) {  
  9.                 for ( name in object ) {  
  10.                     if ( callback.apply( object[ name ], args ) === false ) {  
  11.                         break;  
  12.                     }  
  13.                 }  
  14.             } else {  
  15.                 for ( ; i < length; ) {  
  16.                     if ( callback.apply( object[ i++ ], args ) === false ) {  
  17.                         break;  
  18.                     }  
  19.                 }  
  20.             }  
  21.   
  22.         // A special, fast, case for the most common use of each  
  23.         } else {  
  24.             if ( isObj ) {  
  25.                 for ( name in object ) {  
  26.                     if ( callback.call( object[ name ], name, object[ name ] ) === false ) {  
  27.                         break;  
  28.                     }  
  29.                 }  
  30.             } else {  
  31.                 for ( var value = object[0];  
  32.                     i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}  
  33.             }  
  34.         }  
  35.   
  36.         return object;  
  37.     }  

Awful

  1. someDivs.each(function() {  
  2.     $('#anotherDiv')[0].innerHTML += $(this).text();  
  3. });  
  1. Searches for anotherDiv for each iteration
  2. Grabs the innerHTML property twice
  3. Creates a new jQuery object, all to access the text of the element.

Better

  1. var someDivs = $('#container').find('.someDivs'),  
  2.       contents = [];  
  3.   
  4. someDivs.each(function() {  
  5.     contents.push( this.innerHTML );  
  6. });  
  7. $('#anotherDiv').html( contents.join('') );  
This way, within the each (for) method, the only task we're performing is adding a new key to an array…as opposed to querying the DOM, grabbing the innerHTML property of the element twice, etc.
This tip is more JavaScript-based in general, rather than jQuery specific. The point is to remember that jQuery doesn't compensate for poor coding.

Document Fragments

While we're at it, another option for these sorts of situations is to use document fragments.
  1. var someUls = $('#container').find('.someUls'),  
  2.     frag = document.createDocumentFragment(),  
  3.     li;  
  4.       
  5. someUls.each(function() {  
  6.     li = document.createElement('li');  
  7.     li.appendChild( document.createTextNode(this.innerHTML) );  
  8.     frag.appendChild(li);  
  9. });  
  10.   
  11. $('#anotherUl')[0].appendChild( frag );  
The key here is that there are multiple ways to accomplish simple tasks like this, and each have their own performance benefits from browser to browser. The more you stick with jQuery and learn JavaScript, you also might find that you refer to JavaScript's native properties and methods more often. And, if so, that's fantastic!
jQuery provides an amazing level of abstraction that you should take advantage of, but this doesn't mean that you're forced into using its methods. For example, in the fragment example above, we use jQuery'seach method. If you prefer to use a for or while statement instead, that's okay too!
With all that said, keep in mind that the jQuery team have heavily optimized this library. The debates about jQuery's each()vs. the native for statement are silly and trivial. If you are using jQuery in your project, save time and use their helper methods. That's what they're there for! :)

7. AJAX Methods

If you're just now beginning to dig into jQuery, the various AJAX methods that it makes available to us might come across as a bit daunting; though they needn't. In fact, most of them are simply helper methods, which route directly to $.ajax.
  • get
  • getJSON
  • post
  • ajax
As an example, let's review getJSON, which allows us to fetch JSON.
  1. $.getJSON('path/to/json'function(results) {  
  2.     // callback  
  3.     // results contains the returned data object  
  4. });  
Behind the scenes, this method first calls $.get.
  1. getJSON: function( url, data, callback ) {  
  2.     return jQuery.get(url, data, callback, "json");  
  3. }  
$.get then compiles the passed data, and, again, calls the "master" (of sorts) $.ajax method.
  1. get: function( url, data, callback, type ) {  
  2.     // shift arguments if data argument was omited  
  3.     if ( jQuery.isFunction( data ) ) {  
  4.         type = type || callback;  
  5.         callback = data;  
  6.         data = null;  
  7.     }  
  8.   
  9.     return jQuery.ajax({  
  10.         type: "GET",  
  11.         url: url,  
  12.         data: data,  
  13.         success: callback,  
  14.         dataType: type  
  15.     });  
  16. }  
Finally, $.ajax performs a massive amount of work to allow us the ability to successfully make asynchronous requests across all browsers!
What this means is that you can just as well use the $.ajaxmethod directly and exclusively for all your AJAX requests. The other methods are simply helper methods that end up doing this anyway. So, if you want, cut out the middle man. It's not a significant issue either way.

Just Dandy

  1. $.getJSON('path/to/json'function(results) {  
  2.     // callback  
  3.     // results contains the returned data object  
  4. });  

Microscopically More Efficient

  1. $.ajax({  
  2.     type: 'GET',  
  3.     url : 'path/to/json',  
  4.     data : yourData,  
  5.     dataType : 'json',  
  6.     success : function( results ) {  
  7.         console.log('success');  
  8.     })  
  9. });  

8. Accessing Native Properties and Methods

So you've learned a bit of JavaScript, and have learned that, for instance, on anchor tags, you can access attribute values directly:
  1. var anchor = document.getElementById('someAnchor');  
  2.  //anchor.id  
  3. // anchor.href  
  4. // anchor.title  
  5. // .etc  
The only problem is that this doesn't seem to work when you reference the DOM elements with jQuery, right? Well of course not.

Won't Work

  1. // Fails  
  2. var id = $('#someAnchor').id;  
So, should you need to access the href attribute (or any other native property or method for that matter), you have a handful of options.
  1. // OPTION 1 - Use jQuery  
  2. var id = $('#someAnchor').attr('id');  
  3.   
  4. // OPTION 2 - Access the DOM element  
  5. var id = $('#someAnchor')[0].id;  
  6.   
  7. // OPTION 3 - Use jQuery's get method  
  8. var id = $('#someAnchor').get(0).id; 
  9.  
  10. // OPTION 3b - Don't pass an index to get  
  11. anchorsArray = $('.someAnchors').get();  
  12. var thirdId = anchorsArray[2].id;  
The get method is particularly helpful, as it can translate your jQuery collection into an array.

9. Detect AJAX Requests with PHP

Certainly, for the huge majority of our projects, we can't only rely on JavaScript for things like validation, or AJAX requests. What happens when JavaScript is turned off? For this very reason, a common technique is to detect whether an AJAX request has been made with your server-side language of choice.
jQuery makes this ridiculously simple, by setting a header from within the $.ajax method.
  1. // Set header so the called script knows that it's an XMLHttpRequest  
  2. // Only send the header if it's not a remote XHR  
  3. if ( !remote ) {  
  4.     xhr.setRequestHeader("X-Requested-With""XMLHttpRequest");  
  5. }  
With this header set, we can now use PHP (or any other language) to check for this header, and proceed accordingly. For this, we check the value of $_SERVER['HTTP_X_REQUESTED_WITH'].

Wrapper

  1. function isXhr() {  
  2.   return $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';  
  3. }  

10. jQuery and $

Ever wonder why/how you can use jQuery and $ interchangeably? To find your answer, view the jQuery source, and scroll to the very bottom. There, you'll see:
  1. window.jQuery = window.$ = jQuery;  
The entire jQuery script is, of course, wrapped within a self-executing function, which allows the script to limit the number of global variables as much as possible. What this also means, though, is that the jQuery object is not available outside of the wrapping anonymous function.
To fix this, jQuery is exposed to the global window object, and, in the process, an alias - $ - is also created.

11. Conditionally Loading jQuery

HTML5 Boilerplate offers a nifty one-liner that will load a local copy of jQuery if, for some odd reason, your chosen CDN is down.
  1. <!-- Grab Google CDN jQuery. fall back to local if necessary -->  
  2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>  
  3. <script>!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script>  
To "phrase" the code above: if window.jQuery is undefined, there must have been a problem downloading the script from the CDN. In that case, proceed to the right side of the && operator, and insert a script linking to a local version of jQuery.

12. jQuery Filters

  1. <script>  
  2.     $('p:first').data('info''value'); // populates $'s data object to have something to work with  
  3.       
  4.     $.extend(  
  5.         jQuery.expr[":"], {  
  6.             block: function(elem) {  
  7.                 return $(elem).css("display") === "block";  
  8.             },  
  9.               
  10.             hasData : function(elem) {                
  11.                 return !$.isEmptyObject( $(elem).data() );  
  12.             }  
  13.         }  
  14.     );  
  15.       
  16.     $("p:hasData").text("has data"); // grabs paras that have data attached  
  17.     $("p:block").text("are block level"); // grabs only paragraphs that have a display of "block"  
  18. </script>  
Note: jQuery.expr[':'] is simply an alias forjQuery.expr.filters.

13. A Single Hover Function

As of jQuery 1.4, we can now pass only a single function to the hover method. Before, both the in and outmethods were required.

Before

  1. $('#someElement').hover(function() {  
  2.   // mouseover  
  3. }, function() {  
  4.  // mouseout  
  5. });  

Now

  1. $('#someElement').hover(function() {  
  2.   // the toggle() method can be used here, if applicable  
  3. });  
Note that this isn't an old vs. new deal. Many times, you'll still need to pass two functions to hover, and that's perfectly acceptable. However, if you only need to toggle some element (or something like that), passing a single anonymous function will save a handful of characters or so!

14. Passing an Attribute Object

As of jQuery 1.4, we can now pass an object as the second parameter of the jQuery function. This is helpful when we need to insert new elements into the DOM. For example:

Before

  1. $('<a />')  
  2.   .attr({  
  3.     id : 'someId',  
  4.     className : 'someClass',  
  5.     href : 'somePath.html'  
  6.   });  

After

  1. $('</a>', {  
  2.     id : 'someId',  
  3.     className : 'someClass',  
  4.     href : 'somePath.html'  
  5. });  
Not only does this save a few characters, but it also makes for cleaner code. In addition to element attributes, we can even pass jQuery specific attributes and events, like click or text.

Popular Posts