jQuery Functions and Techniques to Keep in Mind

Nowadays jQuery is used in so many sites that we can’t even count them. There is a reason, jQuery is probably the most famous JavaScript framework.

As developers we have to think beyond. We should be able to use the most advanced techniques of every language or framework we want to know. Here I’ll explain to you some of the good practices and techniques we should be using right now for taking advantage of all this framework can offer us.

Advanced Selectors

In jQuery we can use a lot of selectors, making them very accurate. Let’s see step by step some of them and try to get the point to be able to use them in other contexts.

Selectors based on attributes

Almost every element in HTML can have attributes, for instance:

<img border="0" alt="" />
<input name="email" size="80" type="text" />

In only two html elements we have 9 attributes. With jQuery we can select the elements knowing their attributes and values. Take a look at this selectors:

You can see many others very similar to these ones, in the official documentation. But the point is the same, attributes and theirs values.

Multiple selectors

If you are working on an extensive site, the selectors can become hard. Sometimes it’s better just split them into two or three selectors to make the code easier. Actually this is a very simple and basic thing but it’s truly useful, and we have always to keep it in mind.

$(document).ready(function(){
	//All the images whose width is 600px OR height is 400px
	$("img[width=600],img[height=400]").click(function(){
	   alert("Selected an image whose width is 600px OR height is 400px");
	});

	//All p elements with class orange_text, divs and images.
	$("p.orange_text, div, img").hover(function(){
		alert("Selected a p element with class orange_text, a div OR an image.");
	});	

	//We can also combine the attributes selectors
	//All the jpg images with an alt attribute (the alt's value doesn't matter)
	$("img[alt][src$='.jpg']").click(function(){
	   alert("You selected a jpg image with the alt attribute.");
	});
});

Widget selectors

As well as the usual selectors there are a few ones based on some attributes or positions of elements.Let’s see the more important ones:

$(document).ready(function(){
	//All the hidden images are shown
	$("img:hidden").show();       

	//The first p is going to be orange
	$("p:first").css("color","orange");

	//Input with type password
	//this is $("input[type='password']")
	$("input:password").focus(function(){
	   alert("This is a password!");
	});                  

    //Divs with paragraph
	$("div:has(p)").css("color","green");

	//We can also combine them. with ()
	//All not disabled checkboxes
	$("input:checkbox(:not(:disabled))").hover(function(){
	   alert("This checkbox is working.");
	}); 

});

As you can see we have a wide spectrum of selectors, and they aren’t independent so we can combine them (like the last example).

Understanding the Structure of a Site

I know it could seem complicated but actually it’s not at all and we have to do it if we want to use some selectors and, therefore, methods that work on them.

We can see a site as a reversed tree, with the root at the top and the rest of elements coming from there. Take a look at this code and try to imagine a tree, whose root is the body tag.

...
<div id="wrapper">
<div id="main">
<h1>Create an Account!</h1>
<form id="myform" action="#" method="post">
Personal Information

				<input name="email_address" type="text" value="Email Address" />
				<input name="checking" type="checkbox" />
			</form>

Message</div>
<!--End main--></div>
<!--End wrapper-->
<div id="footer">

Footer message</div>
<!--End footer-->

Let’s see this code as a tree:

HTML as a tree

Easy, right? So from now on we have to see the (x)html as a tree, but why all this theory about botanic if we want to be developers? The answer is in the next point.

Selecting and Transforming the Tree

Selecting

Just like in a tree there are parents and children. In jQuery we can take advantage of this structure. Imagine we have the same html, but now we want to select the p inside the div with id “main”, but we don’t want to change anything about the p element (in fact, if we were going to change it just for the jQuery code were a bad practice.)

Selecting from the tree

Here we’ve got 3 possible solutions:

$("#wrapper").children('#main').children('p').css("color","orange"); 

$("#wrapper").children().children('p').css("color","orange"); 

$("#main").children('p').css("color","orange");

The children method allows you to select an element which is under of other element in the tree. If we pass it a selector, the method will select only the elements we want, but if we don’t all the children of a parent will be selected.

Take a look at the difference between the first and the second selector. The only difference is we specify nothing in the second one so every single children will be selected. The point here is if we see the sketch, we don’t have any other children under the div wrapper, that’s the reason we are getting the same effect.

Adding elements

Now we are going to add an element to our tree. This element could be a paragraph, a div, a form or any other, let’s imagine we want to add a list, something like:

<ul>
	<li>Dog</li>
	<li>Cat</li>
	<li>Frog</li>
</ul>

That’s just a string, so we can have it in that way in our JavaScript code:

var list = "
<ul>\n"
   		 	+ "
	<li>Dog</li>
\n"
			+ "
	<li>Cat</li>
\n"
			+ "
	<li>Frog</li>
\n"
	 		"</ul>
";

Now we have to add that string to the html somewhere. For instance. after the p element we have selected before.

Removing elements

And finally we can type the whole code:

$(document).ready(function(){
	var list = "
<ul>\n"
	   		 	+ "
	<li>Dog</li>
\n"
				+ "
	<li>Cat</li>
\n"
				+ "
	<li>Frog</li>
\n"
		 		"</ul>
";       

   $("#wrapper").children('#main').append(list);
});

We are literally appending the string to the </p> in the HTML, the result is that the list is shown after the p element.

Removing elements

This is not difficult at all, but it has to be here if we are talking about transforming the tree.

Let’s remove the famous paragraph which we selected before (notice we can reuse the selector).

$("#wrapper").children('#main').children('p').remove();

Be careful because with this code all the elements inside the one we select will be removed. If we have a div with a list inside and we remove the div the consequence is both div and list will be removed.

Looking under the hood

jQuery is like an iceberg, there is a lot of things under the surface, some of them are shown in this section.

Bind

Bind is a method which allows us to attach an event (click, hover, focus…) to a method. It’s like saying: “When the user clicks here then call this method”.

It sounds familiar, doesn’t it? That’s because we are using constantly. Take a look at this example:

$(document).ready(function(){
   $("#id").click(function(){
	 alert("That click was amazing!");
   });
});

Well, that click() method, is a wrapper for this code:

$(document).ready(function(){
  $('#id').bind('click', function () {
	alert("That click was amazing!");
  });
});

We can also unbind an event from an element with the unbind() method.

Defining your own jQuery method

So far we have seen some methods, such as click, bind, hover….etc, but how can we make our own methods and call them with something like: $(‘selector’).mymethod()?

The solution is below. Let’s make a method for alerting the value of an element:

//The name will be alertVal
jQuery.fn.alertVal = function() {
    var element = $(this[0]); //That's our element
	if (element.val())
		alert(element.val()); //That's our element's value
};

//This is the way we can use it
$("selector").alertVal();

Callbacks are usually the solution

Callbacks allow us to execute a method when other finishes. You can imagine the callback method says to the other: “When you finish call me, because I have to do my work.”

But now the question is: how can we use them?

$(document).ready(function(){
	myCallBack = function(){
		alert("I'm a callback alert.");
	}   

  //When the get finishes then myCallBack is executed
  $.get('myhtmlpage.html', myCallBack);

});

If the function has arguments remember we have to do it in this way:

$(document).ready(function(){
  $.get('myhtmlpage.html',function(){
	myCallBack(param1, param2);
  });
});

Conclusion

These are only some techniques for getting better knowledge about jQuery. Of course there are a lot of other techniques more advanced than these ones, but take this post as the first step to become a really good jQuery developer.

By the way, jQuery has a great documentation so check the links out.

Image by Shutterstock

The Testking 650-393 online training is the best source to advanced jquery techniques. Download Testking 70-685 design tutorials with expert Testking 642-681 reviews to get unique design ideas.

This entry was posted on Friday, May 7th, 2010 at 20:45 and is filed under Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

I'm from Spain. I've been working in an Internet company for more than a year, I love everything about Internet, from designing to PHP.

About the author Published by Jose

27 Responses »

  1. nice tut, but the techniques you mentioned aren’t advance, most of them are basic use of functions and selectors mentioned in the jquery docs… and I think above you meant traversing not transforming the tree..

  2. they are advanced to me 😀

    And as stated inside his Conclusion;

    These are only some techniques for getting better knowledge about jQuery. Of course there are a lot of other techniques more advanced than these ones, but take this post as the first step to become a really good jQuery developer.

  3. @Abhin Sharma. Advanced is not an absolute term. It depends on how much you know, so there is no advanced or basic things about programming, just known or unknown. Anyway if you know nothing about jQuery you can’t understand the tutorial. That’s why I used the word advanced and not basic.

    And about transforming or traversing, I wanted to introduce the “tree”, so I thought it’d be better just called in a familiar way, with transforming.

    Thanks for the comment!

  4. I don’t see jquery selectors (excluding the one with an id) as a good programming pratice.

    HTML document become complex very fast, with hundred, thousand of elements. I know that doing something with the image of width of 600px was just an exemple, but it’s typicaly something you DON’T want to do.

    In an ideal case, when you make a web app, you don’t have to do that sort of bad things. In fact, it’s mainly usefull if you hack on a code base you can’t change or control.

    But then the code is difficult to maintain and undesterdand, and it’ll produce hard to find bugs.

  5. @Nicolas. Yes, you’re right, but sometimes you can’t change the HTML code, for instance if you work in a company with a design department apart from yours, and you want to select something from the DOM you need a complex selector instead of just change the element with an attribute you like. In an ideal case, as you suggest, you don’t have to do that, but sometimes you can’t change some parts of a project and it’s always useful to keep these “tools” in mind. Thank you for the comment! 🙂

  6. The first section about selecting children is actually pretty inefficient. Instead of:
    $("#wrapper").children('#main').children('p').css("color","orange");
    Why not use:
    $("#wrapper > #main > p").css("color","orange");
    Not only is it more succinct, but it will run quicker. The reason this works is that jQuer selector strings support the same syntax as CSS selectors. Separating things by gt signs is literally the same as the children method. You can also separate by spaces to search ALL children of a node, and not just the ones one level down. Here’s the official w3c list of selectors. Not sure all of them work with jQuery, but most of them (even the obscure ones) do. http://www.w3.org/TR/CSS2/selector.html

    Even this example is a bit silly, though. Element IDs are by definition supposed to be unique in an HTML doc (otherwise use classes), so there’s no reason to select the #main element of the #wrapper class. There’s only one #main element in the first place, so just use $(‘#main > p’).

  7. @Jose well for any technology basic and advance topics exists. Though there are no clear boundaries to differentiate but writing advance topic and pointing out basic api docs is not right. I know your intent was to present the best way possible to readers, but only folks with good knowledge of jquery will read the article, instead you could have written ” Tips of beginners ” that might have worked out. There are mistakes in the article itself, that might mislead beginners,

  8. I’m going to ignore the fact that this article was probably only written to get traffic, and that the title doesn’t appear to make any sense nor bear any relation to the content beneath. I’m going to ignore these things because I think it would benefit the readers more if I simply outlined the technical inaccuracies being sold as fact, and while I wish I could go into considerable depth by writing my own article to counter and expand upon every single item you mention, I simply don’t have time. So, I am sorry (to the readers) — I know this comment will not fully repair the damage done by this article.

    Why, in the first example, are you choosing to alert the message only when certain events occur? What you’re trying to teach is the jQuery’s selector API, so why not just focus on that, and not confuse readers with unnecessary document-ready functions and pointless event handlers? Using document-ready isn’t essential and is certainly not the best way to get code running when the DOM “is ready” — it’s best to place scripts at the bottom of the document, – this also has the added benefit of not blocking loading of other resources. I don’t expect you to go into detail on this — I only mentioned it because you’re using jQuery’s psuedo-ready-event in almost every code snippet. It doesn’t need to be used. What you’re doing to convincing beginners that you can only use jQuery if you use the “ready” event, which is obviously untrue.

    I’ve never heard the term “widget selectors” before — I’m not sure what you’re referring to. In this section you’re just listing a bunch of pointless selectors that might as well have been randomly generated — you don’t explain them very well either.

    I’m amazed how you mention the “structure of a site” and then go on to reference a “reversed tree” yet nowhere in this article do you mention the “DOM”… I’m amazed. Also, surely it would be best to re-order the article, so that the DOM is explained before jQuery’s selector API?

    “The children method allows you to select an element which is under of other element in the tree” – nope. An element that is “under” another element could be described as a descendant, and the children() methods just selects _children_, not all descendants.

    Under the “Adding elements” section you describe a way of appending new elements to the DOM. It would have made sense to describe different ways of creating elements and appending them to the DOM. Putting a bunch of HTML in a string and passing it to a jQuery method is quick-and-easy but it is not scalable. A beginner reading this section might determine that this is the only way to create elements, which is untrue.

    $(“#wrapper”).children(‘#main’) – it would make more sense to just select “main” straight off: $(“#main”)…

    It would be helpful to beginners, when explaining how to “define your own jQuery method”, if you could outline the best practices involved and in what situations one might want to create a jQuery plugin. You might want to cover the fact that, in order to make your new method “chainable”, you should return the jQuery instance. Also, you normally shouldn’t assume that “this” only contains one element. It’s common practice to employ the “each” iterator to access each and every element within the current collection (i.e. the jQuery instance accessed via “this”).

    Please get someone who speaks English natively to proofread your articles in the future.

  9. @padolsey

    Sorry for causing any problems, it was absolutely not our intention to mislead anybody. I’ve changed the title of this post to something more suitable.

    And as mentioned on Twitter, feel free to submit.

  10. @Benjamin Goering. Hello, actually I wanted to point there is a whole structure we can traverse. It’s just an example to point that, not something you can take and put into your project. And about the 2 selectors, yes, the second one is more efficient, but I wanted to be consistent and show the reader the same way I used before.

    @Abhin Sharma. Please, if you see any mistake you can notify and I’ll fix it as soon as possible.

  11. Hi Jos�!

    Thanks for writing this article.

    Please remember something, no matter how much criticism you receive from people who simply like to tear up others’ hard work, you must keep going. This article is being given away for free, and not being Sold, in the commercial sense of the word. Anyone having a problem should thus simply stop reading and leave, instead of disheartening someone having good intentions with negative and personally demeaning comments.

    It is obvious that you are not having many months’ experience in writing articles, given that you’ve been working as a web professional since only an year. But that does not matter. You made an effort to give back something to the internet, and I appreciate that effort. Please keep posting more articles in the future, and keep trying to improve the quality of your output as much as possible.

    All the best 🙂

  12. @James Padolsey. The document-ready function is a good practice if you are using an element of the DOM, and that’s because you need to be sure that the DOM is completely “ready”. Of course you don’t need it but when I’ve used it it was because of that. You can see in the official documentation of the ready event:

    The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code

    (here).

    Regarding to the widget selectors, you are probably right, I should have explained them more.

    The DOM is a concept a little bit more complicated than just a few divs, so I wanted to focus on the jQuery. Besides of that the DOM has more to do with JavaScript than only with a framework. More information about the DOM can be found here.

    About the children method I wasn’t enough accurate, I meant the immediate children. You’re right.

    Again, (in “Adding elements”), I just wanted to show an example. The generation of HTML from jQuery can cover a whole tutorial. Apart from that you’ve said:

    “A beginner reading this section might determine that this is the only way to create elements, which is untrue.”

    Actually I’ve never said that, and it was quicker just writing the HTML in a string var.

    The selection of the children was just to point we can traverse the HTML. But, of course it’d be more efficient what you’ve said.

    And about the definition of our own method in jQuery, the each iterator isn’t needed in this simple example, but as you have pointed, it’s usually better to use it.

    Thanks for the comment. 😉

  13. I believe something went wrong with the code highlighter, just fixed it and updated the code inside this post

  14. Nice article. Examples are spelled out well. Thanks.

  15. @Thanks, really appreciatte it.

  16. Not a bad tutorial but I have to concur with Abin Shama that it’s not advanced.Because if this is advanced, what’s basic then? I think stuff like event binding/unbinding to dynamic content borders into advanced areas. BTW i’m not a hardcore javascript guru.
    This is not to disparage you in anyway so thanks for writing the tutorial. I think the title of the article is a bit misleading and tends to take away the good parts of the tutorial. Nevertheless the article is very readable.

  17. @Jose, No, you don’t need the document-ready event — it’s not necessary at all actually. I’m absolutely fine with people using it but I don’t understand why all of your examples have to be littered with it.

    You say that you wanted to focus on jQuery, but you seemed to drift off into DOM-tree territory, and so I was merely surprised that you didn’t mention the “DOM” at all. I appreciate your intent to gently introduce beginners, but I feel that it’s important to tread cautiously when doing so and certainly pay special attention to correct terminology and best practices. I feel this article was lacking in these areas.

  18. @James Padolsey. The document-ready event has a lot of advantages and is a good practice. If you don’t trust me (obviously you don’t :D), please, trust Karl Swedberg. (here).

    If you want an event to work on your page, you should call it inside the $(document).ready() function

    He’s on the jQuery project team and has written some books about jQuery.

    I respect your opinion and appreciate your comments.

    I try to do my best and keep learning. Thank you!

  19. Thanks for the article

    @others who are criticising : if you don’t like the article, just leave it. It depends on the developer to use his own set of code-handling style. Its their own personal opinion. Why can’t you emphasize on writing your own blog with more ‘pro-developer’ knowledge of yours. Never criticise people who are willing and taking steps to contribute instead of sitting idle for their own sake with their much earned knowledge.

    Jose, your effort in this age is really appreciated. Keep it up!

  20. Can’t say the article was helpfull for me personally but I did send it troughout the office here. It explains the power of the jquery selectors and how to use them. So props for the article.

  21. @Jose, yes, I know Karl. I actually wrote on his site (learningjquery.com) not so long ago. If you contacted Karl I’m quite confident that he would agree with me on the fact that document-ready isn’t necessary all the time — and that’s it’s faster to use alternative techniques (such as the one I outlined in my initial comment). I’m grateful that you “respect” my opinion, but most of what I’ve written isn’t opinion, but fact. Please do your research.

  22. @James Padolsey. We need the document-ready event only when we work with other events, and even in those cases, there are other techniques.

    Besides of that I haven’t said we have to use it every time we code something in jQuery, but if I haven’t said where to put the code I’ve written, the best way to make sure the DOM is ready is to use the Document-ready event, in that way people can put the code wherever they want.

    There isn’t an example with HTML and jQuery code together in this tutorial, if there were one, you could see the jQuery at the bottom without the document-ready event.

    Thanks for the contribution. 😉

  23. @James, it’s not worth arguing over this… Yeah I know I’m not one to talk, but still…

  24. @Evan Byrne. Well, I think it is, that’s the point of comments, isn’t it? Thanks for reading! 😉

  25. The selectors in the first paragraph ‘Selectors based on attributes’ seem to be missing??

  26. hey

    cool list.I have also 70+ jQuery Best Interface Techniques and Tutorials.Please see

    http://jquery13.blogspot.com/2010/08/70-jquery-best-interface-techniques-and.html

    Thanks
    Aman