HTML and CSS Reference
In-Depth Information
</form>
</section>
<script src="jquery-1.8.1.js"></script>
</body>
</html>
6. Save the file.
Now that you have a test page set up, let's look at some of the ways that using jQuery can make writing JavaScript
programs easier.
Executing Code on Page Load
In pure JavaScript, you can tell the browser to execute some code when the page loads by attaching a function to the
window.onload event. The following code shows how this would be done:
window.onload = function() {
// Do something here.
}
jQuery provides an alternative way of doing this, as shown here:
$(function() {
// Do something here.
});
The dollar ( $ ) symbol at the beginning of this code represents the jQuery object. This object provides a number of
helper functions that can take care of common tasks, such as selecting elements and updating the content of those
elements.
Many developers (including me) prefer to use the jQuery method of executing code when the page has loaded, even
though the syntax itself does not make much sense to humans.
Selecting Elements
The jQuery library provides a simpler way of selecting page elements that is very popular with developers. Instead
of using the getElementsBy... functions, you can simply pass a selector to the jQuery object and it will return
the page element or an array of page elements. If you are familiar with CSS, jQuery uses the same syntax as CSS se-
lectors for referring to IDs and classes. Let me show you some examples comparing the pure JavaScript selectors to
jQuery selectors. Load your new test page and try these out in the developer tools console.
To select an element by its ID in jQuery, you use the # sign followed by the ID:
// Select an element by its ID.
document.getElementById(“text"); // Pure JavaScript
$(“#text"); // jQuery
Using jQuery, you can select all elements within a certain class by placing a period before the class name:
// Select all elements with a class.
document.getElementsByClassName(“paragraph"); // Pure JavaScript
$(“.paragraph"); // jQuery
Search WWH ::




Custom Search