Create DOM elements on-the-fly from the provided String of raw HTML.
jQuery
Creates a div element (and all of its contents) dynamically, and appends it to the element with the ID of body. Internally, an element is created and it's innerHTML property set to the given markup. It is therefore both quite flexible and limited.
$("<div><p>Hello</p></div>").appendTo("#body")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).
jQuery
Sets the background color of the page to black.
$(document.body).background( "black" );
Hides all the input elements within a form
$( myForm.elements ).hide()
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 all of the other $() operations on your page. 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.
jQuery
Executes the function when the DOM is ready to be used.
$(function(){
// Document is ready
});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...
});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, $() looks for DOM elements within the context of the current HTML document.
jQuery
Finds all p elements that are children of a div element.
$("div > p")<p>one</p> <div><p>two</p></div> <p>three</p>
[ <p>two</p> ]
Searches for all inputs of type radio within the first form in the document
$("input:radio", document.forms[0])This finds all div elements within the specified XML document.
$("div", xml.responseXML)Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to add plugin methods (plugins).
Object
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();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; }
});Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.
By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p").
undefined
Maps the original object that was referenced by $ back to $
jQuery.noConflict();
// Do something with jQuery
jQuery("div p").hide();
// Do something with another library's $()
$("content").style.display = 'none';Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.
jQuery.noConflict();
(function($) {
$(function() {
// more code using $ as alias to jQuery
});
})(jQuery);
// other code using $ as an alias to the other libraryExecute 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 element.
Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set.
jQuery
Iterates over two images and sets their src property
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});<img/><img/>
<img src="test0.jpg"/><img src="test1.jpg"/>
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.
jQuery
$("p").eq(1)<p>This is just a test.</p><p>So is this</p>
[ <p>So is this</p> ]
Access all matched 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).
Array<Element>
Selects all images in the document and returns the DOM Elements as an Array
$("img").get();<img src="test1.jpg"/> <img src="test2.jpg"/>
[ <img src="test1.jpg"/> <img src="test2.jpg"/> ]
Access a single matched element. num is used to access the Nth element matched.
Element
Selects all images in the document and returns the first one
$("img").get(0);<img src="test1.jpg"/> <img src="test2.jpg"/>
[ <img src="test1.jpg"/> ]
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.
jQuery
$("p").gt(0)<p>This is just a test.</p><p>So is this</p>
[ <p>So is this</p> ]
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.
Number
Returns the index for the element with ID foobar
$("*").index( $('#foobar')[0] )<div id="foobar"><b></b><span id="foo"></span></div>
0
Returns the index for the element with ID foo within another element
$("*").index( $('#foo')[0] )<div id="foobar"><b></b><span id="foo"></span></div>
2
Returns -1, as there is no element with ID bar
$("*").index( $('#bar')[0] )<div id="foobar"><b></b><span id="foo"></span></div>
-1
The number of elements currently matched.
Number
$("img").length;<img src="test1.jpg"/> <img src="test2.jpg"/>
2
Reduce the set of matched elements to all elements before a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.
jQuery
$("p").lt(1)<p>This is just a test.</p><p>So is this</p>
[ <p>This is just a test.</p> ]
The number of elements currently matched.
Number
$("img").size();<img src="test1.jpg"/> <img src="test2.jpg"/>
2
Adds the specified class(es) to each of the set of matched elements.
jQuery
$("p").addClass("selected")<p>Hello</p>
[ <p class="selected">Hello</p> ]
$("p").addClass("selected highlight")<p>Hello</p>
[ <p class="selected highlight">Hello</p> ]
Access a property on the first matched element. This method makes it easy to retrieve a property value from the first matched element.
Object
Returns the src attribute from the first image in the document.
$("img").attr("src");<img src="test.jpg"/>
test.jpg
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.
jQuery
Sets src and alt attributes to all images.
$("img").attr({ src: "test.jpg", alt: "Test Image" });<img/>
<img src="test.jpg" alt="Test Image"/>
Set a single property to a value, on all matched elements.
Can compute values provided as ${formula}, see second example.
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.
jQuery
Sets src attribute to all images.
$("img").attr("src","test.jpg");<img/>
<img src="test.jpg"/>
Sets title attribute from src attribute, a shortcut for attr(String,Function)
$("img").attr("title", "${this.src}");<img src="test.jpg" />
<img src="test.jpg" title="test.jpg" />
Set a single property to a computed value, on all matched elements.
Instead of a value, a function is provided, that computes the value.
jQuery
Sets title attribute from src attribute.
$("img").attr("title", function() { return this.src });<img src="test.jpg" />
<img src="test.jpg" title="test.jpg" />
Get the html contents of the first matched element. This property is not available on XML documents.
String
$("div").html();<div><input/></div>
<input/>
Set the html contents of every matched element. This property is not available on XML documents.
jQuery
$("div").html("<b>new stuff</b>");<div><input/></div>
<div><b>new stuff</b></div>
Remove an attribute from each of the matched elements.
jQuery
$("input").removeAttr("disabled")<input disabled="disabled"/>
<input/>
Removes all or the specified class(es) from the set of matched elements.
jQuery
$("p").removeClass()<p class="selected">Hello</p>
[ <p>Hello</p> ]
$("p").removeClass("selected")<p class="selected first">Hello</p>
[ <p class="first">Hello</p> ]
$("p").removeClass("selected highlight")<p class="highlight selected first">Hello</p>
[ <p class="first">Hello</p> ]
Get the text contents of all matched elements. The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents.
String
Gets the concatenated text of all paragraphs
$("p").text();<p><b>Test</b> Paragraph.</p><p>Paraparagraph</p>
Test Paragraph.Paraparagraph
Set the text contents of all matched elements.
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).
String
Sets the text of all paragraphs.
$("p").text("<b>Some</b> new text.");<p>Test Paragraph.</p>
<p><b>Some</b> new text.</p>
Sets the text of all paragraphs.
$("p").text("<b>Some</b> new text.", true);<p>Test Paragraph.</p>
<p>Some new text.</p>
Adds the specified class if it is not present, removes it if it is present.
jQuery
$("p").toggleClass("selected")<p>Hello</p><p class="selected">Hello Again</p>
[ <p class="selected">Hello</p>, <p>Hello Again</p> ]
Get the current value of the first matched element.
String
$("input").val();<input type="text" value="some text"/>
"some text"
Set the value of every matched element.
jQuery
$("input").val("test");<input type="text" value="some text"/>
<input type="text" value="test"/>
Insert content after each of the matched elements.
jQuery
Inserts some HTML after all paragraphs.
$("p").after("<b>Hello</b>");<p>I would like to say: </p>
<p>I would like to say: </p><b>Hello</b>
Inserts an Element after all paragraphs.
$("p").after( $("#foo")[0] );<b id="foo">Hello</b><p>I would like to say: </p>
<p>I would like to say: </p><b id="foo">Hello</b>
Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs.
$("p").after( $("b") );<b>Hello</b><p>I would like to say: </p>
<p>I would like to say: </p><b>Hello</b>
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.
jQuery
Appends some HTML to all paragraphs.
$("p").append("<b>Hello</b>");<p>I would like to say: </p>
<p>I would like to say: <b>Hello</b></p>
Appends an Element to all paragraphs.
$("p").append( $("#foo")[0] );<p>I would like to say: </p><b id="foo">Hello</b>
<p>I would like to say: <b id="foo">Hello</b></p>
Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").append( $("b") );<p>I would like to say: </p><b>Hello</b>
<p>I would like to say: <b>Hello</b></p>
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.
jQuery
Appends all paragraphs to the element with the ID "foo"
$("p").appendTo("#foo");<p>I would like to say: </p><div id="foo"></div>
<div id="foo"><p>I would like to say: </p></div>
Insert content before each of the matched elements.
jQuery
Inserts some HTML before all paragraphs.
$("p").before("<b>Hello</b>");<p>I would like to say: </p>
<b>Hello</b><p>I would like to say: </p>
Inserts an Element before all paragraphs.
$("p").before( $("#foo")[0] );<p>I would like to say: </p><b id="foo">Hello</b>
<b id="foo">Hello</b><p>I would like to say: </p>
Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
$("p").before( $("b") );<p>I would like to say: </p><b>Hello</b>
<b>Hello</b><p>I would like to say: </p>
Clone matched DOM Elements and select the clones.
This is useful for moving copies of the elements to another location in the DOM.
jQuery
Clones all b elements (and selects the clones) and prepends them to all paragraphs.
$("b").clone().prependTo("p");<b>Hello</b><p>, how are you?</p>
<b>Hello</b><p><b>Hello</b>, how are you?</p>
Removes all child nodes from the set of matched elements.
jQuery
$("p").empty()<p>Hello, <span>Person</span> <a href="#">and person</a></p>
[ <p></p> ]
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.
jQuery
Same as $("#foo").after("p")
$("p").insertAfter("#foo");<p>I would like to say: </p><div id="foo">Hello</div>
<div id="foo">Hello</div><p>I would like to say: </p>
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.
jQuery
Same as $("#foo").before("p")
$("p").insertBefore("#foo");<div id="foo">Hello</div><p>I would like to say: </p>
<p>I would like to say: </p><div id="foo">Hello</div>
Prepend content to the inside of every matched element.
This operation is the best way to insert elements inside, at the beginning, of all matched elements.
jQuery
Prepends some HTML to all paragraphs.
$("p").prepend("<b>Hello</b>");<p>I would like to say: </p>
<p><b>Hello</b>I would like to say: </p>
Prepends an Element to all paragraphs.
$("p").prepend( $("#foo")[0] );<p>I would like to say: </p><b id="foo">Hello</b>
<p><b id="foo">Hello</b>I would like to say: </p>
Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").prepend( $("b") );<p>I would like to say: </p><b>Hello</b>
<p><b>Hello</b>I would like to say: </p>
Prepend all of the matched elements to another, specified, set of elements. This operation is, essentially, the reverse of doing a regular $(A).prepend(B), in that instead of prepending B to A, you're prepending A to B.
jQuery
Prepends all paragraphs to the element with the ID "foo"
$("p").prependTo("#foo");<p>I would like to say: </p><div id="foo"><b>Hello</b></div>
<div id="foo"><p>I would like to say: </p><b>Hello</b></div>
Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use the matched elements further.
Can be filtered with an optional expressions.
jQuery
$("p").remove();<p>Hello</p> how are <p>you?</p>
how are
$("p").remove(".hello");<p class="hello">Hello</p> how are <p>you?</p>
how are <p>you?</p>
Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.
This works by going through the first element provided (which is generated, on the fly, from the provided HTML) and finds the deepest ancestor element within its structure - it is that element that will en-wrap everything else.
This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.
jQuery
$("p").wrap("<div class='wrap'></div>");<p>Test Paragraph.</p>
<div class='wrap'><p>Test Paragraph.</p></div>
Wrap all matched elements with a structure of other elements. This wrapping process is most useful for injecting additional stucture into a document, without ruining the original semantic qualities of a document.
This works by going through the first element provided and finding the deepest ancestor element within its structure - it is that element that will en-wrap everything else.
This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.
jQuery
$("p").wrap( document.getElementById('content') );<p>Test Paragraph.</p><div id="content"></div>
<div id="content"><p>Test Paragraph.</p></div>
Adds more elements, matched by the given expression, to the set of matched elements.
jQuery
$("p").add("span")<p>Hello</p><span>Hello Again</span>
[ <p>Hello</p>, <span>Hello Again</span> ]
Adds more elements, created on the fly, to the set of matched elements.
jQuery
$("p").add("<span>Again</span>")<p>Hello</p>
[ <p>Hello</p>, <span>Again</span> ]
Adds one or more Elements to the set of matched elements.
jQuery
$("p").add( document.getElementById("a") )<p>Hello</p><p><span id="a">Hello Again</span></p>
[ <p>Hello</p>, <span id="a">Hello Again</span> ]
$("p").add( document.forms[0].elements )<p>Hello</p><p><form><input/><button/></form>
[ <p>Hello</p>, <input/>, <button/> ]
Get a set of elements containing all of the unique children of each of the matched set of elements.
Can be filtered with an optional expressions.
jQuery
Find all children of each div.
$("div").children()<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
[ <span>Hello Again</span> ]
Find all children with a class "selected" of each div.
$("div").children(".selected")<div><span>Hello</span><p class="selected">Hello Again</p><p>And Again</p></div>
[ <p class="selected">Hello Again</p> ]
Filter the set of elements to those that contain the specified text.
jQuery
$("p").contains("test")<p>This is just a test.</p><p>So is this</p>
[ <p>This is just a test.</p> ]
End the most recent 'destructive' operation, reverting the list of matched elements back to its previous state. After an end operation, the list of matched elements will revert to the last state of matched elements.
If there was no destructive operation before, an empty set is returned.
jQuery
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
$("p").find("span").end();<p><span>Hello</span>, how are you?</p>
[ <p>...</p> ]
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.
jQuery
Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")<p class="selected">Hello</p><p>How are you?</p>
[ <p class="selected">Hello</p> ]
Selects all paragraphs and removes those without class "selected" and being the first one.
$("p").filter(".selected, :first")<p>Hello</p><p>Hello Again</p><p class="selected">And Again</p>
[ <p>Hello</p>, <p class="selected">And Again</p> ]
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.
jQuery
Remove all elements that have a child ol element
$("p").filter(function(index) {
return $("ol", this).length == 0;
})<p><ol><li>Hello</li></ol></p><p>How are you?</p>
[ <p>How are you?</p> ]
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.
jQuery
Starts with all paragraphs and searches for descendant span elements, same as $("p span")
$("p").find("span");<p><span>Hello</span>, how are you?</p>
[ <span>Hello</span> ]
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.
Boolean
Returns true, because the parent of the input is a form element
$("input[@type='checkbox']").parent().is("form")<form><input type="checkbox" /></form>
true
Returns false, because the parent of the input is a p element
$("input[@type='checkbox']").parent().is("form")<form><p><input type="checkbox" /></p></form>
false
Get a set of elements containing the unique next siblings of each of the matched set of elements.
It only returns the very next sibling, not all next siblings.
Can be filtered with an optional expressions.
jQuery
Find the very next sibling of each paragraph.
$("p").next()<p>Hello</p><p>Hello Again</p><div><span>And Again</span></div>
[ <p>Hello Again</p>, <div><span>And Again</span></div> ]
Find the very next sibling of each paragraph that has a class "selected".
$("p").next(".selected")<p>Hello</p><p class="selected">Hello Again</p><div><span>And Again</span></div>
[ <p class="selected">Hello Again</p> ]
Removes the specified Element from the set of matched elements. This method is used to remove a single Element from a jQuery object.
jQuery
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not( $("#selected")[0] )<p>Hello</p><p id="selected">Hello Again</p>
[ <p>Hello</p> ]
Removes elements matching the specified expression from the set of matched elements. This method is used to remove one or more elements from a jQuery object.
jQuery
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not("#selected")<p>Hello</p><p id="selected">Hello Again</p>
[ <p>Hello</p> ]
Removes any elements inside the array of elements from the set of matched elements. This method is used to remove one or more elements from a jQuery object.
jQuery
Removes all elements that match "div p.selected" from the total set of all paragraphs.
$("p").not( $("div p.selected") )<div><p>Hello</p><p class="selected">Hello Again</p></div>
[ <p>Hello</p> ]
Get a set of elements containing the unique parents of the matched set of elements.
Can be filtered with an optional expressions.
jQuery
Find the parent element of each paragraph.
$("p").parent()<div><p>Hello</p><p>Hello</p></div>
[ <div><p>Hello</p><p>Hello</p></div> ]
Find the parent element of each paragraph with a class "selected".
$("p").parent(".selected")<div><p>Hello</p></div><div class="selected"><p>Hello Again</p></div>
[ <div class="selected"><p>Hello Again</p></div> ]
Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
Can be filtered with an optional expressions.
jQuery
Find all parent elements of each span.
$("span").parents()<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
[ <body>...</body>, <div>...</div>, <p><span>Hello</span></p> ]
Find all parent elements of each span that is a paragraph.
$("span").parents("p")<html><body><div><p><span>Hello</span></p><span>Hello Again</span></div></body></html>
[ <p><span>Hello</span></p> ]
Get a set of elements containing the unique previous siblings of each of the matched set of elements.
Can be filtered with an optional expressions.
It only returns the immediately previous sibling, not all previous siblings.
jQuery
Find the very previous sibling of each paragraph.
$("p").prev()<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
[ <div><span>Hello Again</span></div> ]
Find the very previous sibling of each paragraph that has a class "selected".
$("p").prev(".selected")<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
[ <div><span>Hello</span></div> ]
Get a set of elements containing all of the unique siblings of each of the matched set of elements.
Can be filtered with an optional expressions.
jQuery
Find all siblings of each div.
$("div").siblings()<p>Hello</p><div><span>Hello Again</span></div><p>And Again</p>
[ <p>Hello</p>, <p>And Again</p> ]
Find all siblings with a class "selected" of each div.
$("div").siblings(".selected")<div><span>Hello</span></div><p class="selected">Hello Again</p><p>And Again</p>
[ <p class="selected">Hello Again</p> ]
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.
String
Retrieves the color style of the first paragraph
$("p").css("color");<p style="color:red;">Test Paragraph.</p>
"red"
Retrieves the font-weight style of the first paragraph.
$("p").css("font-weight");<p style="font-weight: bold;">Test Paragraph.</p>
"bold"
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.
jQuery
Sets color and background styles to all p elements.
$("p").css({ color: "red", background: "blue" });<p>Test Paragraph.</p>
<p style="color:red; background:blue;">Test Paragraph.</p>
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.
jQuery
Changes the color of all paragraphs to red
$("p").css("color","red");<p>Test Paragraph.</p>
<p style="color:red;">Test Paragraph.</p>
Changes the left of all paragraphs to "30px"
$("p").css("left",30);<p>Test Paragraph.</p>
<p style="left:30px;">Test Paragraph.</p>
Get the current computed, pixel, height of the first matched element.
String
$("p").height();<p>This is just a test.</p>
300
Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.
jQuery
$("p").height(20);<p>This is just a test.</p>
<p style="height:20px;">This is just a test.</p>
$("p").height("20em");<p>This is just a test.</p>
<p style="height:20em;">This is just a test.</p>
Get the current computed, pixel, width of the first matched element.
String
$("p").width();<p>This is just a test.</p>
300
Set the CSS width of every matched element. If no explicit unit was specified (like 'em' or '%') then "px" is added to the width.
jQuery
$("p").width(20);<p>This is just a test.</p>
<p style="width:20px;">This is just a test.</p>
$("p").width("20em");<p>This is just a test.</p>
<p style="width:20em;">This is just a test.</p>
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.
Boolean
Returns true if the current useragent is some version of microsoft's internet explorer
$.browser.msie
Alerts "this is safari!" only for safari browsers
if($.browser.safari) { $( function() { alert("this is safari!"); } ); }A generic iterator function, which can be used to seemlessly 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.
Object
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 );
});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 );
});Extend one object with one or more others, returning the original, modified, object. This is a great utility for simple inheritance.
Object
Merge settings and options, modifying settings
var settings = { validate: false, limit: 5, name: "foo" };
var options = { validate: true, name: "bar" };
jQuery.extend(settings, options);settings == { validate: true, limit: 5, name: "bar" }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);settings == { validate: true, limit: 5, name: "bar" }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.
Array
$.grep( [0,1,2], function(i){
return i > 0;
});[1, 2]
Translate all items in an array to another array of items.
The translation function that is provided to this method is called for each item in the array and is passed one argument: The item to be translated.
The function can then return the translated value, 'null' (to remove the item), or an array of values - which will be flattened into the full array.
Array
Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(i){
return i + 4;
});[4, 5, 6]
Maps the original array to a new one and adds 1 to each value if it is bigger then zero, otherwise it's removed-
$.map( [0,1,2], function(i){
return i > 0 ? i + 1 : null;
});[2, 3]
Maps the original array to a new one, each element is added with it's original value and the value plus one.
$.map( [0,1,2], function(i){
return [ i, i + 1 ];
});[0, 1, 1, 2, 2, 3]
Merge two arrays together, removing all duplicates.
The new array is: All the results from the first array, followed by the unique results from the second array.
Array
Merges two arrays, removing the duplicate 2
$.merge( [0,1,2], [2,3,4] )
[0,1,2,3,4]
Merges two arrays, removing the duplicates 3 and 2
$.merge( [3,2,1], [4,3,2] )
[3,2,1,4]
Remove the whitespace from the beginning and end of a string.
String
$.trim(" hello, how are you? ");"hello, how are you?"
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 paramter (and the handler function as the third), see second example.
jQuery
$("p").bind("click", function(){
alert( $(this).text() );
});<p>Hello</p>
alert("Hello")Pass some additional data to the event handler.
function handler(event) {
alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)alert("bar")Cancel a default action and prevent it from bubbling by returning false from your function.
$("form").bind("submit", function() { return false; })Cancel only the default action by using the preventDefault method.
$("form").bind("submit", function(event){
event.preventDefault();
});Stop only an event from bubbling by using the stopPropagation method.
$("form").bind("submit", function(event){
event.stopPropagation();
});Trigger the blur event of each matched element. This causes all of the functions that have been bound to thet blur event to be executed.
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();
jQuery
$("p").blur();<p onblur="alert('Hello');">Hello</p>alert('Hello');Bind a function to the blur event of each matched element.
jQuery
$("p").blur( function() { alert("Hello"); } );<p>Hello</p>
<p onblur="alert('Hello');">Hello</p>Bind a function to the change event of each matched element.
jQuery
$("p").change( function() { alert("Hello"); } );<p>Hello</p>
<p onchange="alert('Hello');">Hello</p>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.
jQuery
$("p").click();<p onclick="alert('Hello');">Hello</p>alert('Hello');Bind a function to the click event of each matched element.
jQuery
$("p").click( function() { alert("Hello"); } );<p>Hello</p>
<p onclick="alert('Hello');">Hello</p>Bind a function to the dblclick event of each matched element.
jQuery
$("p").dblclick( function() { alert("Hello"); } );<p>Hello</p>
<p ondblclick="alert('Hello');">Hello</p>Bind a function to the error event of each matched element.
jQuery
$("p").error( function() { alert("Hello"); } );<p>Hello</p>
<p onerror="alert('Hello');">Hello</p>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();
jQuery
$("p").focus();<p onfocus="alert('Hello');">Hello</p>alert('Hello');Bind a function to the focus event of each matched element.
jQuery
$("p").focus( function() { alert("Hello"); } );<p>Hello</p>
<p onfocus="alert('Hello');">Hello</p>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).
jQuery
$("p").hover(function(){
$(this).addClass("over");
},function(){
$(this).addClass("out");
});Bind a function to the keydown event of each matched element.
jQuery
$("p").keydown( function() { alert("Hello"); } );<p>Hello</p>
<p onkeydown="alert('Hello');">Hello</p>Bind a function to the keypress event of each matched element.
jQuery
$("p").keypress( function() { alert("Hello"); } );<p>Hello</p>
<p onkeypress="alert('Hello');">Hello</p>Bind a function to the keyup event of each matched element.
jQuery
$("p").keyup( function() { alert("Hello"); } );<p>Hello</p>
<p onkeyup="alert('Hello');">Hello</p>Bind a function to the load event of each matched element.
jQuery
$("p").load( function() { alert("Hello"); } );<p>Hello</p>
<p onload="alert('Hello');">Hello</p>Bind a function to the mousedown event of each matched element.
jQuery
$("p").mousedown( function() { alert("Hello"); } );<p>Hello</p>
<p onmousedown="alert('Hello');">Hello</p>Bind a function to the mousemove event of each matched element.
jQuery
$("p").mousemove( function() { alert("Hello"); } );<p>Hello</p>
<p onmousemove="alert('Hello');">Hello</p>Bind a function to the mouseout event of each matched element.
jQuery
$("p").mouseout( function() { alert("Hello"); } );<p>Hello</p>
<p onmouseout="alert('Hello');">Hello</p>Bind a function to the mouseover event of each matched element.
jQuery
$("p").mouseover( function() { alert("Hello"); } );<p>Hello</p>
<p onmouseover="alert('Hello');">Hello</p>Bind a function to the mouseup event of each matched element.
jQuery
$("p").mouseup( function() { alert("Hello"); } );<p>Hello</p>
<p onmouseup="alert('Hello');">Hello</p>Binds a handler to a particular event (like click) for each matched element. The handler is executed only once for each element. Otherwise, the same rules as described in bind() apply. 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 paramter (and the handler function as the third), see second example.
jQuery
$("p").one("click", function(){
alert( $(this).text() );
});<p>Hello</p>
alert("Hello")Bind a function to be executed whenever the DOM is ready to be traversed and manipulated. This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.
In a nutshell, this is a solid replacement for using window.onload, and attaching a function to that. By using this method, your bound Function will be called the instant the DOM is ready to be read and manipulated, which is exactly what 99.99% of all Javascript code needs to run.
There is one argument passed to the ready event handler: A reference to the jQuery function. You can name that argument whatever you like, and can therefore stick with the $ alias without risc of naming collisions.
Please ensure you have no code in your <body> onload event handler, otherwise $(document).ready() may not fire.
You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added.
jQuery
$(document).ready(function(){ Your code here... });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...
});Bind a function to the resize event of each matched element.
jQuery
$("p").resize( function() { alert("Hello"); } );<p>Hello</p>
<p onresize="alert('Hello');">Hello</p>Bind a function to the scroll event of each matched element.