jQuery Basics

Contact Us or call 1-877-932-8228
jQuery Basics

jQuery Basics

jQuery is the JavaScript framework upon which jQuery Mobile is built. Core jQuery "simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development" - offering you, as a developer, both great power and a much simplified API to work with (as compared to plain old JavaScript).

The most basic concept of jQuery is to "select some elements and do something with them". jQuery supports most CSS3 selectors, as well as some nonstandard selectors. (For a complete selector reference, visit the jQuery docs.)

One might, for example, want to find all divs on a page with a given class:


Or to find "list elements within the unordered list element with class people within the element with id contents":

$('#contents ul.people li');

Each of the examples above returns a collection - a set, with zero, one, or more DOM elements - which can be traversed using jQuery.

$('p.highlight').length returns the number of paragraphs of class highlight. This is a good way to test for the existence of a given element, since a length of 0 means the searched-for element does not exist.

We can traverse these collections of elements and manipulate them - remove elements, set displayable-on-the-screen content, update a class or style, etc.

Here's a quick example from the jQuery docs. In a page containing the following markup:

	<li>list item 1</li>
	<li>list item 2</li>
	<li class="third-item">list item 3</li>
	<li>list item 4</li>
	<li>list item 5</li>

We can perform the following using jQuery's next method:

$('li.third-item').next().css('background-color', 'red');

This code says "find the immediately-following sibling [.next] of the list item with class third-item [$('li.third-item')] and set its CSS background-color to the value red [.css('background-color', 'red')]". The result would be a red background for the list with display text "list item 4".

Element-manipulation methods like append , prepend , and remove offer an easy way to dynamically edit content in the DOM with jQuery.

Since the markup we use with jQuery Mobile depends heavily on data-x attributes, the framework makes available an easy way to reference elements like <div data-role="footer">: $("div:jqmData(role='footer')") returns a collection of all footers in your document.

jQuery is a great tool - check out the online documentation and learning resources for more information.