-
$( String html ) returns jQuery
Create DOM elements on-the-fly from the provided String of raw HTML.
Example:
Creates a div element (and all of its contents) dynamically, and appends it to the body element. Internally, an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.
$("<div><p>Hello</p></div>").appendTo("body") -
$( Element|Array<Element> elems ) returns jQuery
Wrap jQuery functionality around a single or multiple DOM Element(s).
This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements).Example:
Sets the background color of the page to black.
$(document.body).css( "background", "black" );Example:
Hides all the input elements within a form
$( myForm.elements ).hide() -
$( Function fn ) returns jQuery
A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.
You can have as many $(document).ready events on your page as you like.
See ready(Function) for details about the ready event.Example:
Executes the function when the DOM is ready to be used.
$(function(){ // Document is ready });Example:
Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.
jQuery(function($) { // Your code using failsafe $ alias here... }); -
$( String expr, Element|jQuery context ) returns jQuery
This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements.
The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS or XPath), which then finds all matching elements.
By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.
See [[DOM/Traversing/Selectors]] for the allowed CSS/XPath syntax for expressions.Example:
Finds all p elements that are children of a div element.
$("div > p")HTML:
<p>one</p> <div><p>two</p></div> <p>three</p>Result:
[ <p>two</p> ]Example:
Searches for all inputs of type radio within the first form in the document
$("input:radio", document.forms[0])Example:
This finds all div elements within the specified XML document.
$("div", xml.responseXML) -
add( String expr ) returns jQuery
Adds more elements, matched by the given expression, to the set of matched elements.
Example:
Compare the above result to the result of <code>$('p')</code>, which would just result in <code><nowiki>[ <p>Hello</p> ]</nowiki></code>. Using add(), matched elements of <code>$('span')</code> are simply added to the returned jQuery-object.
$("p").add("span")HTML:
(HTML) <p>Hello</p><span>Hello Again</span>Result:
(jQuery object matching 2 elements) [ <p>Hello</p>, <span>Hello Again</span> ] -
add( String html ) returns jQuery
Adds more elements, created on the fly, to the set of matched elements.
Example:
$("p").add("<span>Again</span>")HTML:
<p>Hello</p>Result:
[ <p>Hello</p>, <span>Again</span> ] -
add( Element|Array<Element> elements ) returns jQuery
Adds one or more Elements to the set of matched elements.
Example:
$("p").add( document.getElementById("a") )HTML:
<p>Hello</p><p><span id="a">Hello Again</span></p>Result:
[ <p>Hello</p>, <span id="a">Hello Again</span> ]Example:
$("p").add( document.forms[0].elements )HTML:
<p>Hello</p><p><form><input/><button/></form>Result:
[ <p>Hello</p>, <input/>, <button/> ] -
addClass( String class ) returns jQuery
Adds the specified class(es) to each of the set of matched elements.
Example:
$("p").addClass("selected")HTML:
<p>Hello</p>Result:
[ <p class="selected">Hello</p> ]Example:
$("p").addClass("selected highlight")HTML:
<p>Hello</p>Result:
[ <p class="selected highlight">Hello</p> ] -
after( <Content> content ) returns jQuery
Insert content after each of the matched elements.
Example:
Inserts some HTML after all paragraphs.
$("p").after("<b>Hello</b>");HTML:
<p>I would like to say: </p>Result:
<p>I would like to say: </p><b>Hello</b>Example:
Inserts an Element after all paragraphs.
$("p").after( $("#foo")[0] );HTML:
<b id="foo">Hello</b><p>I would like to say: </p>Result:
<p>I would like to say: </p><b id="foo">Hello</b>Example:
Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
$("p").after( $("b") );HTML:
<b>Hello</b><p>I would like to say: </p>Result:
<p>I would like to say: </p><b>Hello</b> -
$.ajax( Map properties ) returns XMLHttpRequest
Load a remote page using an HTTP request.
This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions that are often easier to understand and use, but don't offer as much functionality (such as error callbacks).
$.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually.
'''Note:''' If you specify the dataType option described below, make sure the server sends the correct MIME type in the response (eg. xml as "text/xml"). Sending the wrong MIME type can lead to unexpected problems in your script. See [[Specifying the Data Type for AJAX Requests]] for more information.
Supported datatypes are (see dataType option):
"xml": Returns a XML document that can be processed via jQuery.
"html": Returns HTML as plain text, included script tags are evaluated.
"script": Evaluates the response as Javascript and returns it as plain text.
"json": Evaluates the response as JSON and returns a Javascript Object
$.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These are all the key/values that can be used:
(String) url - The URL to request.
(String) type - The type of request to make ("POST" or "GET"), default is "GET".
(String) dataType - The type of data that you're expecting back from the server. No default: If the server sends xml, the responseXML, otherwise the responseText is passed to the success callback.
(Boolean) ifModified - Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header.
(Number) timeout - Local timeout to override global timeout, eg. to give a single request a longer timeout while all others timeout after 1 second. See $.ajaxTimeout() for global timeouts.
(Boolean) global - Whether to trigger global AJAX event handlers for this request, default is true. Set to false to prevent that global handlers like ajaxStart or ajaxStop are triggered.
(Function) error - A function to be called if the request fails. The function gets passed tree arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occured.
(Function) success - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the 'dataType' parameter.
(Function) complete - A function to be called when the request finishes. The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.
(Object|String) data - Data to be sent to the server. Converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing.
(String) contentType - When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases.
(Boolean) processData - By default, data passed in to the data option as an object other as string will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, set this option to false.
(Boolean) async - By default, all requests are sent asynchronous (set to true). If you need synchronous requests, set this option to false.
(Function) beforeSend - A pre-callback to set custom headers etc., the XMLHttpRequest is passed as the only argument.Example:
Load and execute a JavaScript file.
$.ajax({ type: "GET", url: "test.js", dataType: "script" })Example:
Save some data to the server and notify the user once its complete.
$.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } });Example:
Loads data synchronously. Blocks the browser while the requests is active. It is better to block user interaction by other means when synchronization is necessary.
var html = $.ajax({ url: "some.php", async: false }).responseText;Example:
Sends an xml document as data to the server. By setting the processData option to false, the automatic conversion of data to strings is prevented.
var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: handleResponse }); -
ajaxComplete( Function callback ) returns jQuery
Attach a function to be executed whenever an AJAX request completes.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.Example:
Show a message when an AJAX request completes.
$("#msg").ajaxComplete(function(request, settings){ $(this).append("<li>Request Complete.</li>"); }); -
ajaxError( Function callback ) returns jQuery
Attach a function to be executed whenever an AJAX request fails.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback. A third argument, an exception object, is passed if an exception occured while processing the request.Example:
Show a message when an AJAX request fails.
$("#msg").ajaxError(function(request, settings){ $(this).append("<li>Error requesting page " + settings.url + "</li>"); }); -
ajaxSend( Function callback ) returns jQuery
Attach a function to be executed before an AJAX request is sent.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.Example:
Show a message before an AJAX request is sent.
$("#msg").ajaxSend(function(request, settings){ $(this).append("<li>Starting request at " + settings.url + "</li>"); }); -
$.ajaxSetup( Map settings ) returns undefined
Setup global settings for AJAX requests.
See $.ajax for a description of all available options.Example:
Sets the defaults for AJAX requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following AJAX requests then sends some data without having to set anything else.
$.ajaxSetup( { url: "/xmlhttp/", global: false, type: "POST" } ); $.ajax({ data: myData }); -
ajaxStart( Function callback ) returns jQuery
Attach a function to be executed whenever an AJAX request begins and there is none already active.
Example:
Show a loading message whenever an AJAX request starts (and none is already active).
$("#loading").ajaxStart(function(){ $(this).show(); }); -
ajaxStop( Function callback ) returns jQuery
Attach a function to be executed whenever all AJAX requests have ended.
Example:
Hide a loading message after all the AJAX requests have stopped.
$("#loading").ajaxStop(function(){ $(this).hide(); }); -
ajaxSuccess( Function callback ) returns jQuery
Attach a function to be executed whenever an AJAX request completes successfully.
The XMLHttpRequest and settings used for that request are passed as arguments to the callback.Example:
Show a message when an AJAX request completes successfully.
$("#msg").ajaxSuccess(function(request, settings){ $(this).append("<li>Successful Request!</li>"); }); -
$.ajaxTimeout( Number time ) returns undefined
Set the timeout of all AJAX requests to a specific amount of time. This will make all future AJAX requests timeout after a specified amount of time.
Set to null or 0 to disable timeouts (default).
You can manually abort requests with the XMLHttpRequest's (returned by all ajax functions) abort() method.
Deprecated. Use $.ajaxSetup instead.Example:
Make all AJAX requests timeout after 5 seconds.
$.ajaxTimeout( 5000 ); -
animate( Hash params, String|Number speed, String easing, Function callback ) returns jQuery
A function for making your own, custom animations. The key aspect of this function is the object of style properties that will be animated, and to what end. Each key within the object represents a style property that will also be animated (for example: "height", "top", or "opacity").
Note that properties should be specified using camel case eg. marginLeft instead of margin-left.
The value associated with the key represents to what end the property will be animated. If a number is provided as the value, then the style property will be transitioned from its current state to that new number. Otherwise if the string "hide", "show", or "toggle" is provided, a default animation will be constructed for that property.Example:
$("p").animate({ height: 'toggle', opacity: 'toggle' }, "slow");Example:
$("p").animate({ left: 50, opacity: 'show' }, 500);Example:
An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function (Only 'linear' is provided by default, with jQuery).
$("p").animate({ opacity: 'show' }, "slow", "easein"); -
append( <Content> content ) returns jQuery
Append content to the inside of every matched element.
This operation is similar to doing an appendChild to all the specified elements, adding them into the document.Example:
Appends some HTML to all paragraphs.
$("p").append("<b>Hello</b>");HTML:
<p>I would like to say: </p>Result:
<p>I would like to say: <b>Hello</b></p>Example:
Appends an Element to all paragraphs.
$("p").append( $("#foo")[0] );HTML:
<p>I would like to say: </p><b id="foo">Hello</b>Result:
<p>I would like to say: <b id="foo">Hello</b></p>Example:
Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").append( $("b") );HTML:
<p>I would like to say: </p><b>Hello</b>Result:
<p>I would like to say: <b>Hello</b></p> -
appendTo( <Content> content ) returns jQuery
Append all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).append(B), in that instead of appending B to A, you're appending A to B.
Example:
Appends all paragraphs to the element with the ID "foo"
$("p").appendTo("#foo");HTML:
<p>I would like to say: </p><div id="foo"></div>Result:
<div id="foo"><p>I would like to say: </p></div> -
attr( String name ) returns Object
Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element.
If the element does not have an attribute with such a name, undefined is returned.Example:
Returns the src attribute from the first image in the document.
$("img").attr("src");HTML:
<img src="test.jpg"/>Result:
test.jpg -
attr( Map properties ) returns jQuery
Set a key/value object as properties to all matched elements.
This serves as the best way to set a large number of properties on all matched elements.Example:
Sets src and alt attributes to all images.
$("img").attr({ src: "test.jpg", alt: "Test Image" });HTML:
<img/>Result:
<img src="test.jpg" alt="Test Image"/> -
attr( String key, Object value ) returns jQuery
Set a single property to a value, on all matched elements.
Note that you can't set the name property of input elements in IE. Use $(html) or .append(html) or .html(html) to create elements on the fly including the name property.Example:
Sets src attribute to all images.
$("img").attr("src","test.jpg");HTML:
<img/>Result:
<img src="test.jpg"/> -
attr( String key, Function value ) returns jQuery
Set a single property to a computed value, on all matched elements.
Instead of supplying a string value as described [[DOM/Attributes#attr.28_key.2C_value_.29|above]], a function is provided that computes the value.Example:
Sets title attribute from src attribute.
$("img").attr("title", function() { return this.src });HTML:
<img src="test.jpg" />Result:
<img src="test.jpg" title="test.jpg" />Example:
Enumerate title attribute.
$("img").attr("title", function(index) { return this.title + (i + 1); });HTML:
<img title="pic" /><img title="pic" /><img title="pic" />Result:
<img title="pic1" /><img title="pic2" /><img title="pic3" /> -
before( <Content> content ) returns jQuery
Insert content before each of the matched elements.
Example:
Inserts some HTML before all paragraphs.
$("p").before("<b>Hello</b>");HTML:
<p>I would like to say: </p>Result:
<b>Hello</b><p>I would like to say: </p>Example:
Inserts an Element before all paragraphs.
$("p").before( $("#foo")[0] );HTML:
<p>I would like to say: </p><b id="foo">Hello</b>Result:
<b id="foo">Hello</b><p>I would like to say: </p>Example:
Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
$("p").before( $("b") );HTML:
<p>I would like to say: </p><b>Hello</b>Result:
<b>Hello</b><p>I would like to say: </p> -
bind( String type, Object data, Function fn ) returns jQuery
Binds a handler to a particular event (like click) for each matched element. The event handler is passed an event object that you can use to prevent default behaviour. To stop both default action and event bubbling, your handler has to return false.
In most cases, you can define your event handlers as anonymous functions (see first example). In cases where that is not possible, you can pass additional data as the second parameter (and the handler function as the third), see second example.Example:
$("p").bind("click", function(){ alert( $(this).text() ); });HTML:
<p>Hello</p>Result:
alert("Hello")Example:
Pass some additional data to the event handler.
function handler(event) { alert(event.data.foo); } $("p").bind("click", {foo: "bar"}, handler)Result:
alert("bar")Example:
Cancel a default action and prevent it from bubbling by returning false from your function.
$("form").bind("submit", function() { return false; })Example:
Cancel only the default action by using the preventDefault method.
$("form").bind("submit", function(event){ event.preventDefault(); });Example:
Stop only an event from bubbling by using the stopPropagation method.
$("form").bind("submit", function(event){ event.stopPropagation(); }); -
blur( ) returns jQuery
Trigger the blur event of each matched element. This causes all of the functions that have been bound to that blur event to be executed, and calls the browser's default blur action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the blur event.
Note: This does not execute the blur method of the underlying elements! If you need to blur an element via code, you have to use the DOM method, eg. $("#myinput")[0].blur();Example:
$("p").blur();HTML:
<p onblur="alert('Hello');">Hello</p>Result:
alert('Hello'); -
blur( Function fn ) returns jQuery
Bind a function to the blur event of each matched element.
Example:
$("p").blur( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onblur="alert('Hello');">Hello</p> -
$.browser returns Boolean
Contains flags for the useragent, read from navigator.userAgent. Available flags are: safari, opera, msie, mozilla
This property is available before the DOM is ready, therefore you can use it to add ready events only for certain browsers.
There are situations where object detections is not reliable enough, in that cases it makes sense to use browser detection. Simply try to avoid both!
A combination of browser and object detection yields quite reliable results.Example:
Returns true if the current useragent is some version of microsoft's internet explorer
$.browser.msieExample:
Alerts "this is safari!" only for safari browsers
if($.browser.safari) { $( function() { alert("this is safari!"); } ); } -
change( Function fn ) returns jQuery
Bind a function to the change event of each matched element.
Example:
$("p").change( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onchange="alert('Hello');">Hello</p> -
children( String expr ) returns jQuery
Get a set of elements containing all of the unique children of each of the matched set of elements.
This set can be filtered with an optional expression that will cause only elements matching the selector to be collected.Example:
Find all children of each div.
$("div").children()HTML:
<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>Result:
[ <span>Hello Again</span> ]Example:
Find all children with a class "selected" of each div.
$("div").children(".selected")HTML:
<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>Result:
[ <p class="selected">Hello Again</p> ] -
click( ) returns jQuery
Trigger the click event of each matched element. This causes all of the functions that have been bound to thet click event to be executed.
Example:
$("p").click();HTML:
<p onclick="alert('Hello');">Hello</p>Result:
alert('Hello'); -
click( Function fn ) returns jQuery
Bind a function to the click event of each matched element.
Example:
$("p").click( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onclick="alert('Hello');">Hello</p> -
clone( Boolean deep ) returns jQuery
Clone matched DOM Elements and select the clones.
This is useful for moving copies of the elements to another location in the DOM.Example:
Clones all b elements (and selects the clones) and prepends them to all paragraphs.
$("b").clone().prependTo("p");HTML:
<b>Hello</b><p>, how are you?</p>Result:
<b>Hello</b><p><b>Hello</b>, how are you?</p> -
contains( String str ) returns jQuery
Filter the set of elements to those that contain the specified text.
Example:
$("p").contains("test")HTML:
<p>This is just a test.</p><p>So is this</p>Result:
[ <p>This is just a test.</p> ] -
css( String name ) returns String
Access a style property on the first matched element. This method makes it easy to retrieve a style property value from the first matched element.
Example:
Retrieves the color style of the first paragraph
$("p").css("color");HTML:
<p style="color:red;">Test Paragraph.</p>Result:
"red"Example:
Retrieves the font-weight style of the first paragraph.
$("p").css("font-weight");HTML:
<p style="font-weight: bold;">Test Paragraph.</p>Result:
"bold" -
css( Map properties ) returns jQuery
Set a key/value object as style properties to all matched elements.
This serves as the best way to set a large number of style properties on all matched elements.Example:
Sets color and background styles to all p elements.
$("p").css({ color: "red", background: "blue" });HTML:
<p>Test Paragraph.</p>Result:
<p style="color:red; background:blue;">Test Paragraph.</p> -
css( String key, String|Number value ) returns jQuery
Set a single style property to a value, on all matched elements. If a number is provided, it is automatically converted into a pixel value.
Example:
Changes the color of all paragraphs to red
$("p").css("color","red");HTML:
<p>Test Paragraph.</p>Result:
<p style="color:red;">Test Paragraph.</p>Example:
Changes the left of all paragraphs to "30px"
$("p").css("left",30);HTML:
<p>Test Paragraph.</p>Result:
<p style="left:30px;">Test Paragraph.</p> -
dblclick( Function fn ) returns jQuery
Bind a function to the dblclick event of each matched element.
Example:
$("p").dblclick( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p ondblclick="alert('Hello');">Hello</p> -
each( Function fn ) returns jQuery
Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element.
Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).Example:
Iterates over two images and sets their src property
$("img").each(function(i){ this.src = "test" + i + ".jpg"; });HTML:
<img/><img/>Result:
<img src="test0.jpg"/><img src="test1.jpg"/> -
$.each( Object obj, Function fn ) returns Object
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. This function is not the same as $().each() - which is used to iterate, exclusively, over a jQuery object. This function can be used to iterate over anything.
The callback has two arguments:the key (objects) or index (arrays) as first the first, and the value as the second.Example:
This is an example of iterating over the items in an array, accessing both the current item and its index.
$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });Example:
This is an example of iterating over the properties in an Object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(i, n){ alert( "Name: " + i + ", Value: " + n ); }); -
empty( ) returns jQuery
Removes all child nodes from the set of matched elements.
Example:
$("p").empty()HTML:
<p>Hello, <span>Person</span> <a href="#">and person</a></p>Result:
[ <p></p> ] -
end( ) returns jQuery
Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state (right before the destructive operation).
If there was no destructive operation before, an empty set is returned.
A 'destructive' operation is any operation that changes the set of matched jQuery elements. These functions are: <code>add</code>, <code>children</code>, <code>clone</code>, <code>filter</code>, <code>find</code>, <code>not</code>, <code>next</code>, <code>parent</code>, <code>parents</code>, <code>prev</code> and <code>siblings</code>.Example:
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
$("p").find("span").end();HTML:
<p><span>Hello</span>, how are you?</p>Result:
[ <p>...</p> ] -
eq( Number pos ) returns jQuery
Reduce the set of matched elements to a single element. The position of the element in the set of matched elements starts at 0 and goes to length - 1.
Example:
$("p").eq(1)HTML:
<p>This is just a test.</p><p>So is this</p>Result:
[ <p>So is this</p> ] -
error( Function fn ) returns jQuery
Bind a function to the error event of each matched element.
Example:
$("p").error( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onerror="alert('Hello');">Hello</p> -
$.extend( Object prop ) returns Object
Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to [[Plugins/Authoring|add plugin methods]] (plugins).
Example:
Adds two plugin methods.
jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } }); $("input[@type=checkbox]").check(); $("input[@type=radio]").uncheck();Example:
Adds two functions into the jQuery namespace
jQuery.extend({ min: function(a, b) { return a < b ? a : b; }, max: function(a, b) { return a > b ? a : b; } }); -
$.extend( Object target, Object prop1, Object propN ) returns Object
Extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.
Example:
Merge settings and options, modifying settings
var settings = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; jQuery.extend(settings, options);Result:
settings == { validate: true, limit: 5, name: "bar" }Example:
Merge defaults and options, without modifying the defaults
var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; var settings = jQuery.extend({}, defaults, options);Result:
settings == { validate: true, limit: 5, name: "bar" } -
fadeIn( String|Number speed, Function callback ) returns jQuery
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.Example:
$("p").fadeIn("slow");Example:
$("p").fadeIn("slow",function(){ alert("Animation Done."); }); -
fadeOut( String|Number speed, Function callback ) returns jQuery
Fade out all matched elements by adjusting their opacity and firing an optional callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.Example:
$("p").fadeOut("slow");Example:
$("p").fadeOut("slow",function(){ alert("Animation Done."); }); -
fadeTo( String|Number speed, Number opacity, Function callback ) returns jQuery
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
Only the opacity is adjusted for this animation, meaning that all of the matched elements should already have some form of height and width associated with them.Example:
$("p").fadeTo("slow", 0.5);Example:
$("p").fadeTo("slow", 0.5, function(){ alert("Animation Done."); }); -
filter( String expression ) returns jQuery
Removes all elements from the set of matched elements that do not match the specified expression(s). This method is used to narrow down the results of a search.
Provide a comma-separated list of expressions to apply multiple filters at once.Example:
Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")HTML:
<p class="selected">Hello</p><p>How are you?</p>Result:
[ <p class="selected">Hello</p> ]Example:
Selects all paragraphs and removes those without class "selected" and being the first one.
$("p").filter(".selected, :first")HTML:
<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>Result:
[ <p>Hello</p>, <p class="selected">And Again</p> ] -
filter( Function filter ) returns jQuery
Removes all elements from the set of matched elements that do not pass the specified filter. This method is used to narrow down the results of a search.
Example:
Remove all elements that have a child ol element
$("p").filter(function(index) { return $("ol", this).length == 0; })HTML:
<p><ol><li>Hello</li></ol></p><p>How are you?</p>Result:
[ <p>How are you?</p> ] -
find( String expr ) returns jQuery
Searches for all elements that match the specified expression. This method is a good way to find additional descendant elements with which to process.
All searching is done using a jQuery expression. The expression can be written using CSS 1-3 Selector syntax, or basic XPath.Example:
Starts with all paragraphs and searches for descendant span elements, same as $("p span")
$("p").find("span");HTML:
<p><span>Hello</span>, how are you?</p>Result:
[ <span>Hello</span> ] -
focus( ) returns jQuery
Trigger the focus event of each matched element. This causes all of the functions that have been bound to thet focus event to be executed.
Note: This does not execute the focus method of the underlying elements! If you need to focus an element via code, you have to use the DOM method, eg. $("#myinput")[0].focus();Example:
$("p").focus();HTML:
<p onfocus="alert('Hello');">Hello</p>Result:
alert('Hello'); -
focus( Function fn ) returns jQuery
Bind a function to the focus event of each matched element.
Example:
$("p").focus( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onfocus="alert('Hello');">Hello</p> -
get( ) returns Array<Element>
Access all matched DOM elements. This serves as a backwards-compatible way of accessing all matched elements (other than the jQuery object itself, which is, in fact, an array of elements).
It is useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions.Example:
Selects all images in the document and returns the DOM Elements as an Array
$("img").get();HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>Result:
[ <img src="test1.jpg"/> <img src="test2.jpg"/> ] -
get( Number num ) returns Element
Access a single matched DOM element at a specified index in the matched set. This allows you to extract the actual DOM element and operate on it directly without necessarily using jQuery functionality on it.
Example:
Selects all images in the document and returns the first one
$("img").get(0);HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>Result:
<img src="test1.jpg"/> -
$.get( String url, Map params, Function callback ) returns XMLHttpRequest
Load a remote page using an HTTP GET request.
This is an easy way to send a simple GET request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.Example:
$.get("test.cgi");Example:
$.get("test.cgi", { name: "John", time: "2pm" } );Example:
$.get("test.cgi", function(data){ alert("Data Loaded: " + data); });Example:
$.get("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); } ); -
$.getIfModified( String url, Map params, Function callback ) returns XMLHttpRequest
Load a remote page using an HTTP GET request, only if it hasn't been modified since it was last retrieved.
Example:
$.getIfModified("test.html");Example:
$.getIfModified("test.html", { name: "John", time: "2pm" } );Example:
$.getIfModified("test.cgi", function(data){ alert("Data Loaded: " + data); });Example:
$.getifModified("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); } ); -
$.getJSON( String url, Map params, Function callback ) returns XMLHttpRequest
Load JSON data using an HTTP GET request.
Example:
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });Example:
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); } ); -
$.getScript( String url, Function callback ) returns XMLHttpRequest
Loads, and executes, a remote JavaScript file using an HTTP GET request.
Warning: Safari <= 2.0.x is unable to evaluate scripts in a global context synchronously. If you load functions via getScript, make sure to call them after a delay.Example:
$.getScript("test.js");Example:
$.getScript("test.js", function(){ alert("Script loaded and executed."); }); -
$.grep( Array array, Function fn, Boolean inv ) returns Array
Filter items out of an array, by using a filter function.
The specified function will be passed two arguments: The current array item and the index of the item in the array. The function must return 'true' to keep the item in the array, false to remove it.Example:
$.grep( [0,1,2], function(i){ return i > 0; });Result:
[1, 2] -
gt( Number pos ) returns jQuery
Reduce the set of matched elements to all elements after a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.
Example:
$("p").gt(0)HTML:
<p>This is just a test.</p><p>So is this</p>Result:
[ <p>So is this</p> ] -
height( ) returns String
Get the current computed, pixel, height of the first matched element.
Example:
$("p").height();HTML:
<p>This is just a test.</p>Result:
300 -
height( String|Number val ) returns jQuery
Set the CSS height of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.
Example:
$("p").height(20);HTML:
<p>This is just a test.</p>Result:
<p style="height:20px;">This is just a test.</p>Example:
$("p").height("20em");HTML:
<p>This is just a test.</p>Result:
<p style="height:20em;">This is just a test.</p> -
hide( ) returns jQuery
Hides each of the set of matched elements if they are shown.
Example:
$("p").hide()HTML:
<p>Hello</p>Result:
[ <p style="display: none">Hello</p> ] -
hide( String|Number speed, Function callback ) returns jQuery
Hide all matched elements using a graceful animation and firing an optional callback after completion.
The height, width, and opacity of each of the matched elements are changed dynamically according to the specified speed.Example:
$("p").hide("slow");Example:
$("p").hide("slow",function(){ alert("Animation Done."); }); -
hover( Function over, Function out ) returns jQuery
A method for simulating hovering (moving the mouse on, and off, an object). This is a custom method which provides an 'in' to a frequent task.
Whenever the mouse cursor is moved over a matched element, the first specified function is fired. Whenever the mouse moves off of the element, the second specified function fires. Additionally, checks are in place to see if the mouse is still within the specified element itself (for example, an image inside of a div), and if it is, it will continue to 'hover', and not move out (a common error in using a mouseout event handler).Example:
$("p").hover(function(){ $(this).addClass("hover"); },function(){ $(this).removeClass("hover"); }); -
html( ) returns String
Get the html contents of the first matched element. This property is not available on XML documents.
Example:
$("div").html();HTML:
<div><input/></div>Result:
<input/> -
html( String val ) returns jQuery
Set the html contents of every matched element. This property is not available on XML documents.
Example:
$("div").html("<b>new stuff</b>");HTML:
<div><input/></div>Result:
<div><b>new stuff</b></div> -
index( Element subject ) returns Number
Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found.
Example:
Returns the index for the element with ID foobar
$("*").index( $('#foobar')[0] )HTML:
<div id="foobar"><b></b><span id="foo"></span></div>Result:
0Example:
Returns the index for the element with ID foo within another element
$("*").index( $('#foo')[0] )HTML:
<div id="foobar"><b></b><span id="foo"></span></div>Result:
2Example:
Returns -1, as there is no element with ID bar
$("*").index( $('#bar')[0] )HTML:
<div id="foobar"><b></b><span id="foo"></span></div>Result:
-1 -
insertAfter( <Content> content ) returns jQuery
Insert all of the matched elements after another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).after(B), in that instead of inserting B after A, you're inserting A after B.
Example:
Same as $("#foo").after("p")
$("p").insertAfter("#foo");HTML:
<p>I would like to say: </p><div id="foo">Hello</div>Result:
<div id="foo">Hello</div><p>I would like to say: </p> -
insertBefore( <Content> content ) returns jQuery
Insert all of the matched elements before another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).before(B), in that instead of inserting B before A, you're inserting A before B.
Example:
Same as $("#foo").before("p")
$("p").insertBefore("#foo");HTML:
<div id="foo">Hello</div><p>I would like to say: </p>Result:
<p>I would like to say: </p><div id="foo">Hello</div> -
is( String expr ) returns Boolean
Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.
Does return false, if no element fits or the expression is not valid.
filter(String) is used internally, therefore all rules that apply there apply here, too.Example:
Returns true, because the parent of the input is a form element
$("input[@type='checkbox']").parent().is("form")HTML:
<form><input type="checkbox" /></form>Result:
trueExample:
Returns false, because the parent of the input is a p element
$("input[@type='checkbox']").parent().is("form")HTML:
<form><p><input type="checkbox" /></p></form>Result:
false -
keydown( Function fn ) returns jQuery
Bind a function to the keydown event of each matched element.
Example:
$("p").keydown( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onkeydown="alert('Hello');">Hello</p> -
keypress( Function fn ) returns jQuery
Bind a function to the keypress event of each matched element.
Example:
$("p").keypress( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onkeypress="alert('Hello');">Hello</p> -
keyup( Function fn ) returns jQuery
Bind a function to the keyup event of each matched element.
Example:
$("p").keyup( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onkeyup="alert('Hello');">Hello</p> -
length returns Number
The number of elements currently matched. The size function will return the same value.
Example:
$("img").length;HTML:
<img src="test1.jpg"/> <img src="test2.jpg"/>Result:
2 -
load( Function fn ) returns jQuery
Bind a function to the load event of each matched element.
Example:
$("p").load( function() { alert("Hello"); } );HTML:
<p>Hello</p>Result:
<p onload="alert('Hello');">Hello</p> -
load( String url, Object params, Function callback ) returns jQuery
Load HTML from a remote file and inject it into the DOM.
Note: Avoid to use this to load scripts, instead use $.getScript. IE strips script tags when there aren't any other characters in front of it.Example:
$("#feeds").load("feeds.html");HTML:
<div id="feeds"></div>Result:
<div id="feeds"><b>45</b> feeds found.</div>Example:
Same as above, but with an additional parameter and a callback that is executed when the data was loaded.
$("#feeds").load("feeds.html", {limit: 25}, function() { alert("The last 25 entries in the feed have been loaded"); } ); - loadIfModified(