This is a trivial example that can be replaced by the :focus pseudoclass in
CSS3, but that’s unsupported in some browsers.
Chaining
Methods on jQuery objects return jQuery objects, which means we can chain
methods indefinitely, like this:
jqueryprimer/simple_selection.html
$("h2").addClass("hidden").removeClass("visible");
Take care not to abuse this—it can make code harder to follow.
A2.4 Creating and Removing Elements
From time to time, we need to create new HTML elements so we can insert
them into our document. We can use the jQuery function to create elements.
This is especially useful when these new elements need events or other
behaviors added.
jqueryprimer/create_elements.html
varinput= $("input");
Although we could use document.createElement("input"); to accomplish this, we can
call additional methods easily if we use the jQuery function.
jqueryprimer/create_elements.html
varelement= $("<p>HelloWorld</p>");
element.css("color","#f00").insertAfter("#header");
This is another example where jQuery’s chaining helps us build and manipu-
late structures quickly.
We also need to remove things from the DOM from time to time. By selecting
an element using the jQuery function, we can easily remove all its children:
jqueryprimer/remove_elements.html
$("#animals").empty();
or remove the element itself:
jqueryprimer/remove_elements.html
$("#animals").remove();
This is quite handy at times when you’re working with a more dynamic web
application.
A2.5 Events
We often need to fire events when users interact with our page, and jQuery
makes this very easy. In jQuery, many common events are simply methods
report erratum • discuss
Creating and Removing Elements • 267
Download from Wow! eBook <www.wowebook.com>