-
add( String, DOMElement, Array<DOMElement> expr ) returns jQuery
Adds more elements, matched by the given expression, to the set of matched elements.
Example:
Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow.
$("div").css("border", "2px solid red") .add("p") .css("background", "yellow");
HTML:
<div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <p>Added this... (notice no border)</p>
Example:
Adds more elements, matched by the given expression, to the set of matched elements.
$("p").add("span").css("background", "yellow");
HTML:
<p>Hello</p><span>Hello Again</span>
Example:
Adds more elements, created on the fly, to the set of matched elements.
$("p").clone().add("<span>Again</span>").appendTo(document.body);
HTML:
<p>Hello</p>
Example:
Adds one or more Elements to the set of matched elements.
$("p").add(document.getElementById("a")).css("background", "yellow");
HTML:
<p>Hello</p><span id="a">Hello Again</span>
-
addClass( String class ) returns jQuery
Adds the specified class(es) to each of the set of matched elements.
Example:
Adds the class 'selected' to the matched elements.
$("p:last").addClass("selected");
HTML:
<p>Hello</p> <p>and</p> <p>Goodbye</p>
Example:
Adds the classes 'selected' and 'highlight' to the matched elements.
$("p:last").addClass("selected highlight");
HTML:
<p>Hello</p> <p>and</p> <p>Goodbye</p>
-
after( String, Element, jQuery 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>
Example:
Inserts a DOM element after all paragraphs.
$("p").after( document.createTextNode("Hello") );
HTML:
<p>I would like to say: </p>
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>
-
ajaxComplete( Function callback ) returns jQuery
Attach a function to be executed whenever an AJAX request completes. This is an <a href='Ajax_Events'>Ajax Event</a>.
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. This is an <a href='Ajax_Events'>Ajax Event</a>.
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. This is an <a href='Ajax_Events'>Ajax Event</a>.
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(evt, request, settings){ $(this).append("<li>Starting request at " + settings.url + "</li>"); });
-
ajaxStart( Function callback ) returns jQuery
Attach a function to be executed whenever an AJAX request begins and there is none already active. This is an <a href='Ajax_Events'>Ajax Event</a>.
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. This is an <a href='Ajax_Events'>Ajax Event</a>.
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. This is an <a href='Ajax_Events'>Ajax Event</a>.
The event object, 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(evt, request, settings){ $(this).append("<li>Successful Request!</li>"); });
-
all( ) returns Array<Element>
Matches all elements.
Most useful when combined with a context to search in.Example:
Finds every element (including head, body, etc).
$("*").css("border","3px solid red");
HTML:
<div>DIV</div> <span>SPAN</span> <p>P <button>Button</button></p>
Example:
A common way to find all elements is to set the 'context' to document.body so elements like head, script, etc are left out.
$("*", document.body).css("border","3px solid red");
-
andSelf( ) returns jQuery
Add the previous selection to the current selection.
Useful for traversing elements, and then adding something that was matched before the last traversion.Example:
Find all divs, and all the paragraphs inside of them, and give them both classnames. Notice the div doesn't have the yellow background color since it didn't use andSelf().
$("div").find("p").andSelf().addClass("border"); $("div").find("p").addClass("background");
HTML:
<div> <p>First Paragraph</p> <p>Second Paragraph</p> </div>
-
animate( Options params, Options options ) 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.Options
Example:
The first button shows how an unqueued animation works. It expands the div out to 90% width '''while''' the font-size is increasing. Once the font-size change is complete, the border animation will begin. The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed.
$("#go1").click(function(){ $("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } ) .animate( { fontSize:"24px" }, 1500 ) .animate( { borderRightWidth:"15px" }, 1500); }); $("#go2").click(function(){ $("#block2").animate( { width:"90%"}, 1000 ) .animate( { fontSize:"24px" } , 1000 ) .animate( { borderLeftWidth:"15px" }, 1000); }); $("#go3").click(function(){ $("#go1").add("#go2").click(); }); $("#go4").click(function(){ $("div").css({width:"", fontSize:"", borderWidth:""}); });
HTML:
<button id="go1">» Animate Block1</button> <button id="go2">» Animate Block2</button> <button id="go3">» Animate Both</button> <button id="go4">» Reset</button> <div id="block1">Block1</div> <div id="block2">Block2</div>
Example:
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
$("p").animate({ "height": "toggle", "opacity": "toggle" }, { duration: "slow" });
Example:
Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it ''outside'' the queue, meaning it will automatically start without waiting for its turn.
$("p").animate({ left: "50px", opacity: 1 }, { duration: 500, queue: false });
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.
$("p").animate({ "opacity": "show" }, { "duration": "slow", "easing": "easein" });
-
animate( Options params, String, Number duration, 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. Only properties that take numeric values are supported (e.g. backgroundColor is not supported by animate()).
As of jQuery 1.2 you can now animate properties by em and % (where applicable). Additionally, in jQuery 1.2, you can now do relative animations - specifying a "''+=''" or "''-=''" in front of the property value to move the element positively, or negatively, relative to the current position.Example:
Click the button to animate the div with a number of different properties.
// Using multiple unit types within one animation. $("#go").click(function(){ $("#block").animate({ width: "70%", opacity: 0.4, marginLeft: "0.6in", fontSize: "3em", borderWidth: "10px" }, 1500 ); });
HTML:
<button id="go">» Run</button> <div id="block">Hello!</div>
Example:
Shows a div animate with a relative move. Click several times on the buttons to see the relative animations queued up.
$("#right").click(function(){ $(".block").animate({"left": "+=50px"}, "slow"); }); $("#left").click(function(){ $(".block").animate({"left": "-=50px"}, "slow"); });
HTML:
<button id="left">«</button> <button id="right">»</button> <div class="block"></div>
Example:
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
$("p").animate({ "height": "toggle", "opacity": "toggle" }, "slow");
Example:
Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds.
$("p").animate({ "left": "50", "opacity": 1 }, 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. Note, this code will do nothing unless the paragraph element is hidden.
$("p").animate({ "opacity": "show" }, "slow", "easein");
-
animated( ) returns Array<Element>
Matches all elements that are currently being animated.
Example:
Change the color of any div that is animated.
$("#run").click(function(){ $("div:animated").toggleClass("colored"); }); function animateIt() { $("#mover").slideToggle("slow", animateIt); } animateIt();
HTML:
<button id="run">Run</button> <div></div> <div id="mover"></div> <div></div>
-
append( String, Element, jQuery 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>
Example:
Appends an Element to all paragraphs.
$("p").append(document.createTextNode("Hello"));
HTML:
<p>I would like to say: </p>
Example:
Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").append( $("b") );
HTML:
<b>Hello</b><p>I would like to say: </p>
-
appendTo( String 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 spans to the element with the ID "foo"
$("span").appendTo("#foo"); // check append() examples
HTML:
<span>I have nothing more to say... </span> <div id="foo">FOO! </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:
Finds the title attribute of the first <em> in the page.
var title = $("em").attr("title"); $("div").text(title);
HTML:
<p> Once there was a <em title="huge, gigantic">large</em> dinosaur... </p> The title of the emphasis is:<div></div>
-
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. Note that you must use 'className' as key if you want to set the class-Attribute. Or use .addClass( class ) or .removeClass( class ).Example:
Set some attributes for all <img>s in the page.
$("img").attr({ src: "/images/hat.gif", title: "jQuery", alt: "jQuery Logo" }); $("div").text($("img").attr("alt"));
HTML:
<img /> <img /> <img /> <div></div>
-
attr( String key, Object value ) returns jQuery
Set a single property to a value, on all matched elements.
Example:
Disables buttons greater than the 0th button.
$("button:gt(0)").attr("disabled","disabled");
HTML:
<button>0th Button</button> <button>1st Button</button> <button>2nd Button</button>
-
attr( String key, Function fn ) returns jQuery
Set a single property to a computed value, on all matched elements.
Instead of supplying a string value as described <a href='#keyvalue'>above</a>, a function is provided that computes the value.Example:
Sets id for divs based on the position in the page.
$("div").attr("id", function (arr) { return "div-id" + arr[0]; }) .each(function () { $("span", this).html("(ID = '<b>" + this.id + "</b>')"); });
HTML:
<div>Zero-th <span></span></div> <div>First <span></span></div> <div>Second <span></span></div>
Example:
Sets src attribute from title attribute on the image.
$("img").attr("src", function() { return "/images/" + this.title; });
HTML:
<img title="hat.gif"/> <img title="hat-old.gif"/> <img title="hat2-old.gif"/>
-
attributeContains( String attribute, String value ) returns Array<Element>
Matches elements that have the specified attribute and it contains a certain value.
Example:
Finds all inputs that with a name attribute that contains 'man' and sets the value with some text.
$("input[name*='man']").val("has man in it!");
HTML:
<input name="man-news" /> <input name="milkman" /> <input name="letterman2" /> <input name="newmilk" />
-
attributeEndsWith( String attribute, String value ) returns Array<Element>
Matches elements that have the specified attribute and it ends with a certain value.
Example:
Finds all inputs with an attribute name that ends with 'letter' and puts text in them.
$("input[name$='letter']").val("a letter");
HTML:
<input name="newsletter" /> <input name="milkman" /> <input name="jobletter" />
-
attributeEquals( String attribute, String value ) returns Array<Element>
Matches elements that have the specified attribute with a certain value.
Example:
Finds all inputs with name 'newsletter' and changes the text of the span next to it.
$("input[name='newsletter']").next().text(" is newsletter");
HTML:
<div> <input type="radio" name="newsletter" value="Hot Fuzz" /> <span>name?</span> </div> <div> <input type="radio" name="newsletter" value="Cold Fusion" /> <span>name?</span> </div> <div> <input type="radio" name="accept" value="Evil Plans" /> <span>name?</span> </div>
-
attributeHas( String attribute ) returns Array<Element>
Matches elements that have the specified attribute.
Example:
Bind a single click that adds the div id to its text.
$("div[id]").one("click", function(){ var idString = $(this).text() + " = " + $(this).attr("id"); $(this).text(idString); });
HTML:
<div>no id</div> <div id="hey">with id</div> <div id="there">has an id</div> <div>nope</div>
-
attributeMultiple( Selector selector1, Selector selector2, Selector selectorN ) returns Array<Element>
Matches elements that have the specified attribute and it contains a certain value.
Example:
Finds all inputs that have an id attribute and whose name attribute ends with man and sets the value.
$("input[id][name$='man']").val("only this one");
HTML:
<input id="man-news" name="man-news" /> <input name="milkman" /> <input id="letterman" name="new-letterman" /> <input name="newmilk" />
-
attributeNotEqual( String attribute, String value ) returns Array<Element>
Matches elements that don't have the specified attribute with a certain value.
Example:
Finds all inputs that don't have the name 'newsletter' and changes the text of the span next to it.
$("input[name!='newsletter']").next().text(" is not newsletter");
HTML:
<div> <input type="radio" name="newsletter" value="Hot Fuzz" /> <span>name?</span> </div> <div> <input type="radio" name="newsletter" value="Cold Fusion" /> <span>name?</span> </div> <div> <input type="radio" name="accept" value="Evil Plans" /> <span>name?</span> </div>
-
attributeStartsWith( String attribute, String value ) returns Array<Element>
Matches elements that have the specified attribute and it starts with a certain value.
Example:
Finds all inputs with an attribute name that starts with 'news' and puts text in them.
$("input[name^='news']").val("news here!");
HTML:
<input name="newsletter" /> <input name="milkman" /> <input name="newsboy" />
-
before( String, Element, jQuery 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> is what I said...</p>
Example:
Inserts a DOM element before all paragraphs.
$("p").before( document.createTextNode("Hello") );
HTML:
<p> is what I said...</p>
Example:
Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs.
$("p").before( $("b") );
HTML:
<p> is what I said...</p><b>Hello</b>
-
bind( String type, Object data, Function fn ) returns jQuery
Binds a handler to a particular event (like click) for each matched element. Can also bind custom events.
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. Note that this will prevent handlers on parent elements from running but not other jQuery handlers on the same element.
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:
Handle click and double-click for the paragraph. Note: the coordinates are window relative so in this case relative to the demo iframe.
$("p").bind("click", function(e){ var str = "( " + e.pageX + ", " + e.pageY + " )"; $("span").text("Click happened! " + str); }); $("p").bind("dblclick", function(){ $("span").text("Double-click happened in " + this.tagName); });
HTML:
<p>Click or double click here.</p> <span></span>
Example:
To display each paragraph's text in an alert box whenever it is clicked:
$("p").bind("click", function(){ alert( $(this).text() ); });
Example:
You can pass some extra data before the event handler:
function handler(event) { alert(event.data.foo); } $("p").bind("click", {foo: "bar"}, handler)
Example:
To cancel a default action and prevent it from bubbling up, return false:
$("form").bind("submit", function() { return false; })
Example:
To 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(); });
Example:
Can bind custom events too.
$("p").bind("myCustomEvent", function(e, myName, myValue){ $(this).text(myName + ", hi there!"); $("span").stop().css("opacity", 1) .text("myName = " + myName) .fadeIn(30).fadeOut(1000); }); $("button").click(function () { $("p").trigger("myCustomEvent", [ "John" ]); });
HTML:
<p>Has an attached custom event.</p> <button>Trigger custom event</button> <span style="display:none;"></span>
-
blur( ) returns jQuery
Triggers 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. The blur event usually fires when an element loses focus either via the pointing device or by tabbing navigationExample:
To triggers the blur event on all paragraphs:
$("p").blur();
-
blur( Function fn ) returns jQuery
Bind a function to the blur event of each matched element.
The blur event fires when an element loses focus either via the pointing device or by tabbing navigation.Example:
To pop up an alert saying "Hello World!" every time any paragraph's blur event triggers:
$("p").blur( function () { alert("Hello World!"); } );
-
change( ) returns jQuery
Triggers the change event of each matched element.
This causes all of the functions that have been bound to that change event to be executed, and calls the browser's default change action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the change event. The change event usually fires when a control loses the input focus and its value has been modified since gaining focus. -
change( Function fn ) returns jQuery
Binds a function to the change event of each matched element.
The change event fires when a control loses the input focus and its value has been modified since gaining focus.Example:
Attaches a change even to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
$("select").change(function () { var str = ""; $("select option:selected").each(function () { str += $(this).text() + " "; }); $("div").text(str); }) .change();
HTML:
<select name="sweets" multiple="multiple"> <option>Chocolate</option> <option selected="selected">Candy</option> <option>Taffy</option> <option selected="selected">Carmel</option> <option>Fudge</option> <option>Cookie</option> </select> <div></div>
Example:
To add a validity test to all text input elements:
$("input[@type='text']").change( function() { // check input for validity here });
-
checkbox( ) returns Array<Element>
Matches all input elements of type checkbox.
Example:
Finds all checkbox inputs.
var input = $(":checkbox").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
checked( ) returns Array<Element>
Matches all elements that are checked.
Example:
Finds all input elements that are checked.
function countChecked() { var n = $("input:checked").length; $("div").text(n + (n == 1 ? " is" : " are") + " checked!"); } countChecked(); $(":checkbox").click(countChecked);
HTML:
<form> <input type="checkbox" name="newsletter" checked="checked" value="Hourly" /> <input type="checkbox" name="newsletter" value="Daily" /> <input type="checkbox" name="newsletter" value="Weekly" /> <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> <input type="checkbox" name="newsletter" value="Yearly" /> </form> <div></div>
Result:
[ <input type="checkbox" name="newsletter" checked="checked" value="Daily" />, <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> ]
-
child( Selector parent, Selector child ) returns Array<Element>
Matches all child elements specified by "child" of elements specified by "parent".
Example:
Finds all children of the element with id "main" which is yellow.
$("#main > *").css("border", "3px double red");
HTML:
<span id="main"> <div></div> <button>Child</button> <div class="mini"></div> <div> <div class="mini"></div> <div class="mini"></div> </div> <div><button>Grand</button></div> <div><span>A Span <em>in</em> child</span></div> <span>A Span in main</span> </span>
-
children( String expr ) returns jQuery
Get a set of elements containing all of the unique immediate 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. Also note: while parents() will look at all ancestors, children() will only consider immediate child elements.Example:
Find all children of the clicked element.
$("#container").click(function (e) { $("*").removeClass("hilite"); var $kids = $(e.target).children(); var len = $kids.addClass("hilite").length; $("#results span:first").text(len); $("#results span:last").text(e.target.tagName); e.preventDefault(); return false; });
HTML:
<div id="container"> <div> <p>This <span>is the <em>way</em> we</span> write <em>the</em> demo,</p> </div> <div> <a href="#"><b>w</b>rit<b>e</b></a> the <span>demo,</span> <button>write the</button> demo, </div> <div> This <span>the way we <em>write</em> the <em>demo</em> so</span> <input type="text" value="early" /> in </div> <p> <span>t</span>he <span>m</span>orning. <span id="results">Found <span>0</span> children in <span>TAG</span>.</span> </p> </div>
Example:
Find all children of each div.
$("div").children().css("border-bottom", "3px double red");
HTML:
<p>Hello (this is a paragraph)</p> <div><span>Hello Again (this span is a child of the a div)</span></div> <p>And <span>Again</span> (in another paragraph)</p> <div>And One Last <span>Time</span> (most text directly in a div)</div>
Example:
Find all children with a class "selected" of each div.
$("div").children(".selected").css("color", "blue");
HTML:
<div> <span>Hello</span> <p class="selected">Hello Again</p> <div class="selected">And Again</div> <p>And One Last Time</p> </div>
-
class( String class ) returns Array<Element>
Matches all elements with the given class.
Example:
Finds the element with the class "myClass".
$(".myClass").css("border","3px solid red");
HTML:
<div class="notMe">div class="notMe"</div> <div class="myClass">div class="myClass"</div> <span class="myClass">span class="myClass"</span>
-
click( ) returns jQuery
Triggers the click event of each matched element.
Causes all of the functions that have been bound to that click event to be executed.Example:
To trigger the click event on all of the paragraphs on the page:
$("p").click();
-
click( Function fn ) returns jQuery
Binds a function to the click event of each matched element.
The click event fires when the pointing device button is clicked over an element. A click is defined as a mousedown and mouseup over the same screen location. The sequence of these events is:<ul><li>mousedown</li><li>mouseup</li><li>click</li></ul>Example:
To hide paragraphs on a page when they are clicked:
$("p").click(function () { $(this).slideUp(); }); $("p").hover(function () { $(this).addClass("hilite"); }, function () { $(this).removeClass("hilite"); });
HTML:
<p>First Paragraph</p> <p>Second Paragraph</p> <p>Yet one more Paragraph</p>
-
clone( ) 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>
-
clone( Boolean true ) returns jQuery
Clone matched DOM Elements, and all their event handlers, and select the clones.
This is useful for moving copies of the elements, and their events, to another location in the DOM.Example:
Create a button that's able to clone itself - and have the clones themselves be clonable.
$("button").click(function(){ $(this).clone(true).insertAfter(this); });
HTML:
<button>Clone Me!</button>
-
contains( String text ) returns Array<Element>
Matches elements which contain the given text.
Example:
Finds all divs containing "John" and underlines them.
$("div:contains('John')").css("text-decoration", "underline");
HTML:
<div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn
-
contents( ) returns jQuery
Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
Example:
Find all the text nodes inside a paragraph and wrap them with a bold tag.
$("p").contents().not("[nodeType=1]").wrap("<b/>");
HTML:
<p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>
Example:
Append some new content into an empty iframe.
$("iframe").contents().find("body").append("I'm in an iframe!");
HTML:
<iframe src="/index-blank.html" width="300" height="100"></iframe>
-
css( String name ) returns String
Return a style property on the first matched element.
Example:
To access the background color of a clicked div.
$("div").click(function () { var color = $(this).css("background-color"); $("#result").html("That div is <span style='color:" + color + ";'>" + color + "</span>."); });
HTML:
<span id="result"> </span> <div style="background-color:blue;"></div> <div style="background-color:rgb(15,99,30);"></div> <div style="background-color:#123456;"></div> <div style="background-color:#f11;"></div>
-
css( Map properties ) returns jQuery
Set a key/value object as style properties to all matched elements.
This is the best way to set several style properties on all matched elements.Example:
To set the color of all paragraphs to red and background to blue:
$("p").hover(function () { $(this).css({ backgroundColor:"yellow", fontWeight:"bolder" }); }, function () { var cssObj = { backgroundColor: "#ddd", fontWeight: "", color: "rgb(0,40,244)" } $(this).css(cssObj); });
HTML:
<p> Move the mouse over a paragraph. </p> <p> Like this one or the one above. </p>
Example:
If the property name includes a "-", put it between quotation marks:
$("p").hover(function () { $(this).css({ "background-color":"yellow", "font-weight":"bolder" }); }, function () { var cssObj = { "background-color": "#ddd", "font-weight": "", color: "rgb(0,40,244)" } $(this).css(cssObj); });
HTML:
<p> Move the mouse over a paragraph. </p> <p> Like this one or the one above. </p>
-
css( String name, String or 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:
To change the color of any paragraph to red on mouseover event.
$("p").mouseover(function () { $(this).css("color","red"); });
HTML:
<p> Just roll the mouse over me. </p> <p> Or me to see a color change. </p>
Example:
To highlight a clicked word in the paragraph.
var words = $("p:first").text().split(" "); var text = words.join("</span> <span>"); $("p:first").html("<span>" + text + "</span>"); $("span").click(function () { $(this).css("background-color","yellow"); });
HTML:
<p> Once upon a time there was a man who lived in a pizza parlor. This man just loved pizza and ate it all the time. He went on to be the happiest man in the world. The end. </p>
-
dblclick( ) returns jQuery
Triggers the dblclick event of each matched element.
This causes all of the functions that have been bound to that dblclick event to be executed, and calls the browser's default dblclick action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the dblclick event. The dblclick event usually fires when the pointing device button is double clicked over an element. -
dblclick( Function fn ) returns jQuery
Binds a function to the dblclick event of each matched element.
The dblclick event fires when the pointing device button is double clicked over an elementExample:
To bind a "Hello World!" alert box the dblclick event on every paragraph on the page:
$("p").dblclick( function () { alert("Hello World!"); });
-
dequeue( ) returns jQuery
Removes a queued function from the front of the queue and executes it.
Example:
Use dequeue to end a custom queue function which allows the queue to keep going.
$("button").click(function () { $("div").animate({left:'+=200px'}, 2000); $("div").animate({top:'0px'}, 600); $("div").queue(function () { $(this).toggleClass("red"); $(this).dequeue(); }); $("div").animate({left:'10px', top:'30px'}, 700); });
HTML:
<button>Start</button> <div></div>
-
descendant( Selector ancestor, Selector descendant ) returns Array<Element>
Matches all descendant elements specified by "descendant" of elements specified by "ancestor".
Example:
Finds all input descendants of forms.
$("form input").css("border", "2px dotted blue");
HTML:
<form> <div>Form is surrounded by the green outline</div> <label>Child:</label> <input name="name" /> <fieldset> <label>Grandchild:</label> <input name="newsletter" /> </fieldset> </form> Sibling to form: <input name="none" />
-
disabled( ) returns Array<Element>
Matches all elements that are disabled.
Example:
Finds all input elements that are disabled.
$("input:disabled").val("this is it");
HTML:
<form> <input name="email" disabled="disabled" /> <input name="id" /> </form>
-
each( Function callback ) 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).
Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).Example:
Iterates over three divs and sets their color property.
$(document.body).click(function () { $("div").each(function (i) { if (this.style.color != "blue") { this.style.color = "blue"; } else { this.style.color = ""; } }); });
HTML:
<div>Click here</div> <div>to iterate through</div> <div>these divs.</div>
Example:
If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:
$("span").click(function () { $("li").each(function(){ $(this).toggleClass("example"); }); });
HTML:
To do list: <span>(click here to change)</span> <ul> <li>Eat</li> <li>Sleep</li> <li>Be merry</li> </ul>
Example:
You can use 'return' to break out of each() loops early.
$("button").click(function () { $("div").each(function (index, domEle) { // domEle == this $(domEle).css("backgroundColor", "yellow"); if ($(this).is("#stop")) { $("span").text("Stopped at div index #" + index); return false; } }); });
HTML:
<button>Change colors</button> <span></span> <div></div> <div></div> <div></div> <div></div> <div id="stop">Stop here</div> <div></div> <div></div> <div></div>
-
element( String element ) returns Array<Element>
Matches all elements with the given name.
Example:
Finds every DIV element.
$("div").css("border","3px solid red");
HTML:
<div>DIV1</div> <div>DIV2</div> <span>SPAN</span>
-
empty( ) returns Array<Element>
Matches all elements that have no children (including text nodes).
Example:
Finds all elements that are empty - they don't have child elements or text.
$("td:empty").text("Was empty!").css('background', 'rgb(255,220,200)');
HTML:
<table border="1"> <tr><td>TD #0</td><td></td></tr> <tr><td>TD #2</td><td></td></tr> <tr><td></td><td>TD#5</td></tr> </table>
-
empty( ) returns jQuery
Remove all child nodes from the set of matched elements.
Note that this function starting with 1.2.2 will also remove all event handlers and internally cached data.Example:
Removes all child nodes (including text nodes) from all paragraphs
$("button").click(function () { $("p").empty(); });
HTML:
<p> Hello, <span>Person</span> <a href="javascript:;">and person</a> </p> <button>Call empty() on above paragraph</button>
-
enabled( ) returns Array<Element>
Matches all elements that are enabled.
Example:
Finds all input elements that are enabled.
$("input:enabled").val("this is it");
HTML:
<form> <input name="email" disabled="disabled" /> <input name="id" /> </form>
-
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, which means any Traversing function that returns a jQuery object - including <a href='Traversing/add'>add</a>, <a href='Traversing/andSelf'>andSelf</a>, <a href='Traversing/children'>children</a>, <a href='Traversing/filter'>filter</a>, <a href='Traversing/find'>find</a>, <a href='Traversing/map'>map</a>, <a href='Traversing/next'>next</a>, <a href='Traversing/nextAll'>nextAll</a>, <a href='Traversing/not'>not</a>, <a href='Traversing/parent'>parent</a>, <a href='Traversing/parents'>parents</a>, <a href='Traversing/prev'>prev</a>, <a href='Traversing/prevAll'>prevAll</a>, <a href='Traversing/siblings'>siblings</a> and <a href='Traversing/slice'>slice</a> - plus the <a href='Manipulation/clone'>clone</a> function (from Manipulation).Example:
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
jQuery.fn.showTags = function (n) { var tags = this.map(function () { return this.tagName; }) .get().join(", "); $("b:eq(" + n + ")").text(tags); return this; }; $("p").showTags(0) .find("span") .showTags(1) .css("background", "yellow") .end() .showTags(2) .css("font-style", "italic");
HTML:
<p> Hi there <span>how</span> are you <span>doing</span>? </p> <p> This <span>span</span> is one of several <span>spans</span> in this <span>sentence</span>. </p> <div> Tags in jQuery object initially: <b></b> </div> <div> Tags in jQuery object after find: <b></b> </div> <div> Tags in jQuery object after end: <b></b> </div>
Example:
Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs.
$("p").find("span").end().css("border", "2px red solid");
HTML:
<p><span>Hello</span>, how are you?</p>
-
eq( Number position ) 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:
Reduces the selection to the second selected element.
$("p").eq(1)
HTML:
<p>This is just a test.</p><p>So is this</p>
Result:
[ <p>So is this</p> ]
-
eq( Number index ) returns Element
Matches a single element by its index.
Example:
Finds the third td. (annoying blink isn't it)
$("td:eq(2)").css("text-decoration", "blink");
HTML:
<table border="1"> <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr> <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr> <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr> </table>
-
eq( Integer index ) 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:
Turn the div with index 2 red by adding an appropriate class.
$("div").eq(2).addClass("red");
HTML:
<div></div> <div></div> <div></div> <div></div> <div></div> <div></div>
-
error( ) returns jQuery
Triggers the error event of each matched element.
This causes all of the functions that have been bound to that error event to be executed, and calls the browser's default error action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the error event. The error event usually fires when an element loses focus either via the pointing device or by tabbing navigation. -
error( Function fn ) returns jQuery
Binds a function to the error event of each matched element.
<p>There is no public standard for the error event. In most browsers, the window object's error event is triggered when a JavaScript error occurs on the page. An image object's error event is triggered when it is set an invalid src attribute - either a non-existent file, or one with corrupt image data.</p><p>If the event is thrown by the window object, the event handler will be passed three parameters: <ol><li>A message describing the event ("varName is not defined", "missing operator in expression", etc.),</li><li>the full URL of the document containing the error, and</li><li>the line number on which the error occured.</li></ol></p>
<p>If the event handler returns true, it signifies that the event was handled, and the browser raises no errors.</p><p>For more information, see: <ul><li>[http://msdn2.microsoft.com/en-us/library/ms536930.aspx msdn - onerror Event]</li><li>[http://developer.mozilla.org/en/docs/DOM:window.onerror Gecko DOM Reference - onerror Event]</li><li>[http://developer.mozilla.org/en/docs/DOM:event Gecko DOM Reference - Event object]</li><li>[http://en.wikipedia.org/wiki/DOM_Events Wikipedia: DOM Events]</ul></p>Example:
To keep a server-side log of JavaScript errors, you might want to:
$(window).error(function(msg, url, line){ jQuery.post("js_error_log.php", { msg: msg, url: url, line: line }); });
Example:
To hide JavaScript errors from the user, you can try:
$(window).error(function(){ return true; });
Example:
To hide the "broken image" icons for your IE users, you can try:
$("img").error(function(){ $(this).hide(); });
-
even( ) returns Array<Element>
Matches even elements, zero-indexed.
Example:
Finds even table rows, matching the first, third and so on (index 0, 2, 4 etc.).
$("tr:even").css("background-color", "#bbbbff");
HTML:
<table border="1"> <tr><td>Row with Index #0</td></tr> <tr><td>Row with Index #1</td></tr> <tr><td>Row with Index #2</td></tr> <tr><td>Row with Index #3</td></tr> </table>
-
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:
Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds.
$(document.body).click(function () { $("div:hidden:first").fadeIn("slow"); });
HTML:
<span>Click here...</span> <div id="one"></div> <div id="two"></div> <div id="three"></div>
Example:
Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top.
$("a").click(function () { $("div").fadeIn(3000, function () { $("span").fadeIn(100); }); return false; });
HTML:
<p> Let it be known that the party of the first part and the party of the second part are henceforth and hereto directed to assess the allegations for factual correctness... (<a href="#">click!</a>) <div><span>CENSORED!</span></div> </p>
-
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:
Animates all paragraphs to fade out, completing the animation within 600 milliseconds.
$("p").click(function () { $("p").fadeOut("slow"); });
HTML:
<p> If you click on this paragraph you'll see it just fade away. </p>
Example:
Fades out spans in one section that you click on.
$("span").click(function () { $(this).fadeOut(1000, function () { $("div").text("'" + $(this).text() + "' has faded!"); $(this).remove(); }); }); $("span").hover(function () { $(this).addClass("hilite"); }, function () { $(this).removeClass("hilite"); });
HTML:
<h3>Find the modifiers - <div></div></h3> <p> If you <span>really</span> want to go outside <span>in the cold</span> then make sure to wear your <span>warm</span> jacket given to you by your <span>favorite</span> teacher. </p>
-
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:
Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds.
$("p:first").click(function () { $(this).fadeTo("slow", 0.33); });
HTML:
<p> Click this paragraph to see it fade. </p> <p> Compare to this one that won't fade. </p>
Example:
Fade div to a random opacity on each click, completing the animation within 200 milliseconds.
$("div").click(function () { $(this).fadeTo("fast", Math.random()); });
HTML:
<p>And this is the library that John built...</p> <div id="one"></div> <div id="two"></div> <div id="three"></div>
Example:
Find the right answer! The fade will take 250 milliseconds and change various styles when it completes.
var getPos = function (n) { return (Math.floor(n) * 90) + "px"; }; $("p").each(function (n) { var r = Math.floor(Math.random() * 3); var tmp = $(this).text(); $(this).text($("p:eq(" + r + ")").text()); $("p:eq(" + r + ")").text(tmp); $(this).css("left", getPos(n)); }); $("div").each(function (n) { $(this).css("left", getPos(n)); }) .css("cursor", "pointer") .click(function () { $(this).fadeTo(250, 0.25, function () { $(this).css("cursor", "") .prev().css({"font-weight": "bolder", "font-style": "italic"}); }); });
HTML:
<p>Wrong</p> <div></div> <p>Wrong</p> <div></div> <p>Right!</p> <div></div>
-
file( ) returns Array<Element>
Matches all input elements of type file.
Example:
Finds all file inputs.
var input = $(":file").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
filter( Expression expr ) 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:
Change the color of all divs then put a border around only some of them.
$("div").css("background", "#c8ebcc") .filter(".middle") .css("border-color", "red");
HTML:
<div></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div></div>
Example:
Selects all paragraphs and removes those without a class "selected".
$("p").filter(".selected")
Example:
Selects all paragraphs and removes those that aren't of class "selected" or the first one.
$("p").filter(".selected, :first")
-
filter( Function fn ) returns jQuery
Removes all elements from the set of matched elements that does not match the specified function.
The function is called with a context equal to the current element (just like <a href='Core/each'>$.each</a>). If the function returns false, then the element is removed - anything else and the element is kept.Example:
Change the color of all divs then put a border two specific ones.
$("div").css("background", "#b4b0da") .filter(function (index) { return index == 1 || $(this).attr("id") == "fourth"; }) .css("border", "3px double red");
HTML:
<div id="first"></div> <div id="second"></div> <div id="third"></div> <div id="fourth"></div> <div id="fifth"></div> <div id="sixth"></div>
Example:
Remove all elements that have a descendant ol element
$("p").filter(function(index) { return $("ol", this).length == 0; });
-
find( String expr ) returns jQuery
Searches for all elements that match the specified <a href='Selectors'>expression</a>. This method is a good way to find additional descendant elements with which to process.
All searching is done using a <a href='Selectors'>jQuery expression</a>. The expression can be written using CSS 1-3 Selector syntax.Example:
Starts with all paragraphs and searches for descendant span elements, same as $("p span")
$("p").find("span").css('color','red');
HTML:
<p><span>Hello</span>, how are you?</p> <p>Me? I'm <span>good</span>.</p>
Example:
Add spans around each word then add a hover and italicize words with the letter '''t'''.
var newText = $("p").text().split(" ").join("</span> <span>"); newText = "<span>" + newText + "</span>"; $("p").html(newText) .find("span") .hover(function () { $(this).addClass("hilite"); }, function () { $(this).removeClass("hilite"); }) .end() .find(":contains('t')") .css({"font-style":"italic", "font-weight":"bolder"});
HTML:
<p> When the day is short find that which matters to you or stop believing </p>
-
first( ) returns Element
Matches the first selected element.
Example:
Finds the first table row.
$("tr:first").css("font-style", "italic");
HTML:
<table> <tr><td>Row 1</td></tr> <tr><td>Row 2</td></tr> <tr><td>Row 3</td></tr> </table>
-
firstChild( ) returns Array<Element>
Matches the first child of its parent.
While <a href='Selectors/first'>:first</a> matches only a single element, this matches more then one: One for each parent.Example:
Finds the first span in each matched div to underline and add a hover state.
$("div span:first-child") .css("text-decoration", "underline") .hover(function () { $(this).addClass("sogreen"); }, function () { $(this).removeClass("sogreen"); });
HTML:
<div> <span>John,</span> <span>Karl,</span> <span>Brandon</span> </div> <div> <span>Glen,</span> <span>Tane,</span> <span>Ralph</span> </div>
-
focus( ) returns jQuery
Triggers the focus event of each matched element.
This causes all of the functions that have been bound to the focus event to be executed. Note that this does not execute the focus method of the underlying elements.Example:
To focus on a login input box with id 'login' on page startup, try:
$(document).ready(function(){ $("#login").focus(); });
-
focus( Function fn ) returns jQuery
Binds a function to the focus event of each matched element.
The focus event fires when an element receives focus either via the pointing device or by tab navigation.Example:
To stop people from writing in text input boxes, try:
$("input[@type=text]").focus(function(){ $(this).blur(); });
-
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 divs in the document and returns the DOM Elements as an Array, then uses the built-in reverse-method to reverse that array.
function disp(divs) { var a = []; for (var i = 0; i < divs.length; i++) { a.push(divs[i].innerHTML); } $("span").text(a.join(" ")); } disp( $("div").get().reverse() );
HTML:
Reversed - <span></span> <div>One</div> <div>Two</div> <div>Three</div>
-
get( Number index ) 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. This function called as $(this).get(0) is the equivalent of using square bracket notation on the jQuery object itself like $(this)[0].Example:
Gives the tag name of the element clicked on.
$("*", document.body).click(function (e) { e.stopPropagation(); var domEl = $(this).get(0); $("span:first").text("Clicked on - " + domEl.tagName); });
HTML:
<span> </span> <p>In this paragraph is an <span>important</span> section</p> <div><input type="text" /></div>
-
gt( Number index ) returns Array<Element>
Matches all elements with an index above the given one.
Example:
Finds TD #5 and higher. Reminder: the indexing starts at 0.
$("td:gt(4)").css("text-decoration", "line-through");
HTML:
<table border="1"> <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr> <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr> <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr> </table>
-
has( Selector selector ) returns Array<Element>
Matches elements which contain at least one element that matches the specified selector.
Example:
Adds the class "test" to all divs that have a paragraph inside of them.
$("div:has(p)").addClass("test");
HTML:
<div><p>Hello in a paragraph</p></div> <div>Hello again! (with no paragraph)</div>
-
hasClass( String class ) returns Boolean
Checks the current selection against a class and returns true, if at least one element of the selection has the given class.
This is an alternative to is("." + class).Example:
Check to see if an element has a specific class, and if so, perform an action.
$("div").click(function(){ if ( $(this).hasClass("protected") ) $(this).animate({ left: -10 }, 75) .animate({ left: 10 }, 75) .animate({ left: -10 }, 75) .animate({ left: 10 }, 75) .animate({ left: 0 }, 75); });
HTML:
<span></span><div class="protected"></div> <span></span><div></div> <span></span><div></div> <span></span><div class="protected"></div>
-
header( ) returns Array<Element>
Matches all elements that are headers, like h1, h2, h3 and so on.
Example:
Adds a background and text color to all the headers on the page.
$(":header").css({ background:'#CCC', color:'blue' });
HTML:
<h1>Header 1</h1> <p>Contents 1</p> <h2>Header 2</h2> <p>Contents 2</p>
-
height( ) returns Integer
Get the current computed, pixel, height of the first matched element.
In jQuery 1.2, this method is able to find the height of the window and document.Example:
Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
function showHeight(ele, h) { $("div").text("The height for the " + ele + " is " + h + "px."); } $("#getp").click(function () { showHeight("paragraph", $("p").height()); }); $("#getd").click(function () { showHeight("document", $(document).height()); }); $("#getw").click(function () { showHeight("window", $(window).height()); });
HTML:
<button id="getp">Get Paragraph Height</button> <button id="getd">Get Document Height</button> <button id="getw">Get Window Height</button> <div> </div> <p> Sample paragraph to test height </p>
-
height( String or Number val ) returns jQuery
Set the CSS height of every matched element.
If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.Example:
To set the height of each div on click to 30px plus a color change.
$("div").one('click', function () { $(this).height(30) .css({cursor:"auto", backgroundColor:"green"}); });
HTML:
<div></div> <div></div> <div></div> <div></div> <div></div>
-
hide( ) returns jQuery
Hides each of the set of matched elements if they are shown.
Same as <a href='Effects/hide#speedcallback'>hide( speed, [callback] )</a> without animations. Doesn't change anything if the selected elements are all hidden.Example:
Hides all paragraphs then the link on click.
$("p").hide(); $("a").click(function () { $(this).hide(); return false; });
HTML:
<p>Hello</p> <a href="#">Click to hide me too</a> <p>Here is another paragraph</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:
Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds.
$("button").click(function () { $("p").hide("slow"); });
HTML:
<button>Hide 'em</button> <p>Hiya</p> <p>Such interesting text, eh?</p>
Example:
Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
$("#hidr").click(function () { $("span:last-child").hide("fast", function () { // use callee so don't have to name the function $(this).prev().hide("fast", arguments.callee); }); }); $("#showr").click(function () { $("span").show(2000); });
HTML:
<button id="hidr">Hide</button> <button id="showr">Show</button> <div> <span>Once</span> <span>upon</span> <span>a</span> <span>time</span> <span>there</span> <span>were</span> <span>three</span> <span>programmers...</span> </div>
Example:
Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time.
for (var i = 0; i < 5; i++) { $("<div>").appendTo(document.body); } $("div").click(function () { $(this).hide(2000, function () { $(this).remove(); }); });
HTML:
<div></div>
-
hover( Function over, Function out ) returns jQuery
Simulates 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:
To add a special style to table cells that are being hovered over, try:
$("li").hover( function () { $(this).append($("<span> ***</span>")); }, function () { $(this).find("span:last").remove(); } );
HTML:
<ul> <li>Milk</li> <li>Bread</li> <li>Chips</li> <li>Socks</li> </ul>
Example:
To add a special style to table cells that are being hovered over, try:
$("td").hover( function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover"); } );
-
html( ) returns String
Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
Example:
Click a paragraph to convert it from html to text.
$("p").click(function () { var htmlStr = $(this).html(); $(this).text(htmlStr); });
HTML:
<p> <b>Click</b> to change the <span id="tag">html</span> </p> <p> to a <span id="text">text</span> node. </p> <p> This <button name="nada">button</button> does nothing. </p>
-
html( ) returns String
Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
Example:
Click a paragraph to convert it from html to text.
$("p").click(function () { var htmlStr = $(this).html(); $(this).text(htmlStr); });
HTML:
<p> <b>Click</b> to change the <span id="tag">html</span> </p> <p> to a <span id="text">text</span> node. </p> <p> This <button name="nada">button</button> does nothing. </p>
-
html( string val ) returns jQuery
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
Example:
Add some html to each div.
$("div").html("<span class='red'>Hello <b>Again</b></span>");
HTML:
<span>Hello</span> <div></div> <div></div> <div></div>
Example:
Add some html to each div then immediately do further manipulations to the inserted html.
$("div").html("<b>Wow!</b> Such excitement..."); $("div b").append(document.createTextNode("!!!")) .css("color", "red");
HTML:
<div></div> <div></div> <div></div>
-
html( string val ) returns jQuery
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
Example:
Add some html to each div.
$("div").html("<span class='red'>Hello <b>Again</b></span>");
HTML:
<span>Hello</span> <div></div> <div></div> <div></div>
Example:
Add some html to each div then immediately do further manipulations to the inserted html.
$("div").html("<b>Wow!</b> Such excitement..."); $("div b").append(document.createTextNode("!!!")) .css("color", "red");
HTML:
<div></div> <div></div> <div></div>
-
id( String id ) returns Element
Matches a single element with the given id attribute.
If the id contains characters like periods or colons you have to escape those characters with backslashes [http://docs.jquery.com/Frequently_Asked_Questions#How_do_I_select_an_element_that_has_weird_characters_in_its_ID.3F].Example:
Finds the element with the id "myDiv".
$("#myDiv").css("border","3px solid red");
HTML:
<div id="notMe"><p>id="notMe"</p></div> <div id="myDiv">id="myDiv"</div>
Example:
Finds the element with the id "myID.entry[1]". See how certain characters must be escaped with backslashes.
$("#myID\\.entry\\[1\\]").css("border","3px solid red");
HTML:
<div id="myID.entry[0]">id="myID.entry[0]"</div> <div id="myID.entry[1]">id="myID.entry[1]"</div> <div id="myID.entry[2]">id="myID.entry[2]"</div>
-
image( ) returns Array<Element>
Matches all input elements of type image.
Example:
Finds all image inputs.
var input = $(":image").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </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:
On click, returns the index (based zero) of that div in the page.
$("div").click(function () { // this is the dom element clicked var index = $("div").index(this); $("span").text("That was div index #" + index); });
HTML:
<span>Click a div!</span> <div>First div</div> <div>Second div</div> <div>Third div</div>
Example:
Returns the index for the element with ID foobar.
$("*").index( $('#foobar')[0] )
HTML:
<div id="foobar"><b></b><span id="foo"></span></div>
Example:
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>
Example:
Returns the index for the element clicked within a collection.
var mainNavLinks = $('ul#mainNav li a'); mainNavLinks.click(function(){alert(mainNavLinks.index(this)0;});
Example:
Returns -1, as there is no element with ID bar.
$("*").index( $('#bar')[0] )
HTML:
<div id="foobar"><b></b><span id="foo"></span></div>
-
input( ) returns Array<Element>
Matches all input, textarea, select and button elements.
Example:
Finds all input elements.
var allInputs = $(":input"); var formChildren = $("form > *"); $("div").text("Found " + allInputs.length + " inputs and the form has " + formChildren.length + " children.") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option</option></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
insertAfter( String 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:
Inserts all paragraphs after an element with id of "foo". Same as $("#foo").after("p")
$("p").insertAfter("#foo"); // check after() examples
HTML:
<p> is what I said... </p><div id="foo">FOO!</div>
-
insertBefore( String 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:
Inserts all paragraphs before an element with id of "foo". Same as $("#foo").before("p")
$("p").insertBefore("#foo"); // check before() examples
HTML:
<div id="foo">FOO!</div><p>I would like to say: </p>
-
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.
If no element fits, or the expression is not valid, then the response will be 'false'.
<a href='Traversing/filter'>filter</a> is used internally, therefore all rules that apply there apply here, as well.Example:
Shows a few ways is() can be used inside an event handler.
$("div").one('click', function () { if ($(this).is(":first-child")) { $("p").text("It's the first div."); } else if ($(this).is(".blue,.red")) { $("p").text("It's a blue or red div."); } else if ($(this).is(":contains('Peter')")) { $("p").text("It's Peter!"); } else { $("p").html("It's nothing <em>special</em>."); } $("p").hide().slideDown("slow"); $(this).css({"border-style": "inset", cursor:"default"}); });
HTML:
<div></div> <div class="blue"></div> <div></div> <div class="red"></div> <div><br/><span>Peter</span></div> <div class="blue"></div> <p> </p>
Example:
Returns true, because the parent of the input is a form element
var isFormParent = $("input[@type='checkbox']").parent().is("form") $("div").text("isFormParent = " + isFormParent);
HTML:
<form><input type="checkbox" /></form> <div></div>
Example:
Returns false, because the parent of the input is a p element
var isFormParent = $("input[@type='checkbox']").parent().is("form") $("div").text("isFormParent = " + isFormParent);
HTML:
<form><p><input type="checkbox" /></p></form> <div></div>
-
jQuery( String html ) returns jQuery
Create DOM elements on-the-fly from the provided String of raw HTML.
You can pass in plain HTML Strings written by hand, create them using some template engine or plugin, or load them via AJAX. There are limitations when creating input elements, see the second example. Also when passing strings that may include slashes (such as an image path), escape the slashes. When creating single elements use the closing tag or XHTML format. For example, to create a span use $("<span/>") or $("<span></span>") instead of without the closing slash/tag.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")
Example:
Do not create <input>-Elements without a type-attribute, due to Microsofts read/write-once-rule for the type-attribute of <input>-elements, see this [http://msdn2.microsoft.com/en-us/library/ms534700.aspx official statement] for details.
// Does NOT work in IE: $("<input/>").attr("type", "checkbox"); // Does work in IE: $("<input type='checkbox'/>");
-
jQuery( Element, Array<Element> elements ) 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()
-
jQuery( Function callback ) returns jQuery
A shorthand for $(document).ready().
Allows 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... });
-
jQuery( String expression, Element, jQuery context ) returns jQuery
This function accepts a string containing a CSS 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), 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 <a href='Selectors'>Selectors</a> for the allowed CSS syntax for expressions.Example:
Finds all p elements that are children of a div element.
$("div > p").css("border", "1px solid gray");
HTML:
<p>one</p> <div><p>two</p></div> <p>three</p>
Result:
[ <p>two</p> ]
Example:
Finds all inputs of type radio within the first form in the document.
$("input:radio", document.forms[0]);
Example:
Finds all div elements within an XML document from an AJAX response.
$("div", xml.responseXML);
-
jQuery.ajax( Options options ) 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).
'''Warning: All POST are converted to GET when 'script' is the dataType.(because it loads script as a dom script tag)'''
$.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 <a href='Specifying_the_Data_Type_for_AJAX_Requests'>Specifying the Data Type for AJAX Requests</a> for more information.
$.ajax() takes one argument, an object of key/value pairs, that are used to initialize and handle the request. See below for a full list of the key/values that can be used.
As of jQuery 1.2, you can load JSON data located on another domain if you specify a [http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/ JSONP] callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.Options
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:
Retrieve the latest version of an HTML page.
$.ajax({ url: "test.html", cache: false, success: function(html){ $("#results").append(html); } });
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 });
-
jQuery.ajaxSetup( Options options ) returns
Setup global settings for AJAX requests.
See <a href='Ajax/jQuery.ajax'>$.ajax</a> 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 });
-
jQuery.boxModel returns Boolean
States if the current page, in the user's browser, is being rendered using the [http://www.w3.org/TR/REC-CSS2/box.html W3C CSS Box Model].
Example:
Returns the box model for the iframe.
$("p").html("The box model for this iframe is: <span>" + jQuery.boxModel + "</span>");
HTML:
<p> </p>
Example:
Returns false if the page is in QuirksMode in Internet Explorer
$.boxModel
Result:
false
-
jQuery.browser returns Map
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 detection is not reliable enough, in such cases it makes sense to use browser detection.
A combination of browser and object detection yields quite reliable results.Example:
Show the browser info.
jQuery.each(jQuery.browser, function(i, val) { $("<div>" + i + " : <span>" + val + "</span>") .appendTo(document.body); });
HTML:
<p>Browser info:</p>
Example:
Returns true if the current useragent is some version of Microsoft's Internet Explorer
$.browser.msie
Example:
Alerts "this is safari!" only for safari browsers
if ($.browser.safari) { alert("this is safari!"); }
-
jQuery.browser.version returns String
The version number of the rendering engine for the user's browser.
Here are some typical results: * Internet Explorer: 6.0, 7.0 * Mozilla/Firefox/Flock/Camino: 1.7.12, 1.8.1.3 * Opera: 9.20 * Safari/Webkit: 312.8, 418.9Example:
Returns the browser version.
$("p").html("The browser version is: <span>" + jQuery.browser.version + "</span>");
HTML:
<p> </p>
Example:
Alerts the version of IE that is being used
if ( $.browser.msie ) alert( $.browser.version ); }
Example:
Often you only care about the "major number," the whole number. This can be accomplished with JavaScript's built-in parseInt() function:
if (jQuery.browser.msie) { alert(parseInt(jQuery.browser.version)); }
-
jQuery.data( Element elem ) returns Number
Returns a unique ID for the element.
Typically this function will only be used internally. It is called automatically when necessary when using the other data() functionality.Example:
Get the store id of an element. It is assigned on the data() function call if one hasn't been assigned yet.
$(document.body).click(function(e) { var id = jQuery.data(e.target); $("span").text(id); });
HTML:
<div>A div</div> <div>Another</div> <p>The id of this div is <span>?</span></p>
-
jQuery.data( Element elem, String name ) returns Any
Returns value at named data store for the element.
Example:
Get the data named "blah" stored at for an element.
$("button").click(function(e) { var adiv = $("div").get(0); var value; switch ($("button").index(this)) { case 0 : value = jQuery.data(adiv, "blah"); break; case 1 : jQuery.data(adiv, "blah", "hello"); value = "Stored!"; break; case 2 : jQuery.data(adiv, "blah", 86); value = "Stored!"; break; case 3 : jQuery.removeData(adiv); value = "Removed!"; break; } $("span").text("" + value); });
HTML:
<div>A div</div> <button>Get "blah" from the div</button> <button>Set "blah" to "hello"</button> <button>Set "blah" to 86</button> <button>Remove "blah" from the div</button> <p>The "blah" value of this div is <span>?</span></p>
-
jQuery.data( Element elem, String name, Any value ) returns Any
Stores the value in the named spot and also returns the value.
This function can be useful for attaching data to elements without having to create a new expando. It also isn't limited to a string. The value can be any format.
To avoid conflicts in plugins, it is usually effective to store one object using the plugin name and put all the necessary information in that object.
<code> var obj = jQuery.data($("#target").get(0), "pluginname", {}); obj[...] = ... </code>Example:
Store then retrieve a value from the div element.
var adiv = $("div").get(0); jQuery.data(adiv, "test", { first: 16, last: "pizza!" }); $("span:first").text(jQuery.data(adiv, "test").first); $("span:last").text(jQuery.data(adiv, "test").last);
HTML:
<div> The values stored were <span></span> and <span></span> </div>
-
jQuery.each( Object object, Function callback ) 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 the first, and the value as the second.
If you wish to break the each() loop at a particular iteration you can do so by making your function return false. Other return values are ignored.Example:
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.
var arr = [ "one", "two", "three", "four", "five" ]; var obj = { one:1, two:2, three:3, four:4, five:5 }; jQuery.each(arr, function() { $("#" + this).text("My id is " + this + "."); return (this != "four"); // will stop running to skip "five" }); jQuery.each(obj, function(i, val) { $("#" + i).append(document.createTextNode(" - " + val)); });
HTML:
<div id="one"></div> <div id="two"></div> <div id="three"></div> <div id="four"></div> <div id="five"></div>
Example:
Iterates over items in an array, accessing both the current item and its index.
$.each( [0,1,2], function(i, n){ alert( "Item #" + i + ": " + n ); });
Example:
Iterates 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 ); });
-
jQuery.extend( Object object ) returns jQuery
Extends the jQuery object itself.
Can be used to add functions into the jQuery namespace. See <a href='Core/jQuery.fn.extend'>jQuery.fn.extend</a> for more information on using this method to add <a href='Plugins/Authoring'>Plugins</a>.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; } });
Result:
jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 5
-
jQuery.extend( Object target, Object object1, Object objectN ) 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 empty = {} var defaults = { validate: false, limit: 5, name: "foo" }; var options = { validate: true, name: "bar" }; var settings = $.extend(empty, defaults, options);
Result:
settings == { validate: true, limit: 5, name: "bar" } empty == { validate: true, limit: 5, name: "bar" }
-
jQuery.fn.extend( Object object ) returns jQuery
Extends the jQuery element set to provide new methods (used to make a typical jQuery plugin).
Can be used to add functions into the to add <a href='Plugins/Authoring'>plugin methods (plugins)</a>.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; }); } });
Result:
$("input[@type=checkbox]").check(); $("input[@type=radio]").uncheck();
-
jQuery.get( String url, Map data, 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:
Request the test.php page, but ignore the return results.
$.get("test.php");
Example:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.get("test.php", { name: "John", time: "2pm" } );
Example:
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){ alert("Data Loaded: " + data); });
Example:
Alert out the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).
$.get("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
-
jQuery.getJSON( String url, Map data, Function callback ) returns XMLHttpRequest
Load JSON data using an HTTP GET request.
As of jQuery 1.2, you can load JSON data located on another domain if you specify a [http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/ JSONP] callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback.
Note: Keep in mind, that lines after this function will be executed before callback.Example:
Loads the four most recent cat pictures from the Flickr JSONP API.
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?", function(data){ $.each(data.items, function(i,item){ $("<img/>").attr("src", item.media.m).appendTo("#images"); if ( i == 3 ) return false; }); });
HTML:
<div id="images"></div>
Example:
Load the JSON data from test.js and access a name from the returned JSON data.
$.getJSON("test.js", function(json){ alert("JSON Data: " + json.users[3].name); });
Example:
Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
$.getJSON("test.js", { name: "John", time: "2pm" }, function(json){ alert("JSON Data: " + json.users[3].name); });
Example:
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.getIfModified("test.php", function(data){ alert("Data Loaded: " + data); });
Example:
Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.getIfModified("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
Example:
list the result of a consultation of pages,php in HTML as an array. by Manuel Gonzalez.
var id=$("#id").attr("value"); $.getJSON("pages.php",{id:id},dates); function dates(datos) { $("#list").html("Name:"+datos[1].name+"<br>"+"Last Name:"+datos[1].lastname+"<br>"+"Address:"+datos[1].address); }
-
jQuery.getScript( String url, Function callback ) returns XMLHttpRequest
Loads, and executes, a local JavaScript file using an HTTP GET request.
Before jQuery 1.2, getScript was only able to load scripts from the same domain as the original page. As of 1.2, you can now load JavaScript files from any domain.
Warning: Safari 2 and older 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:
We load the new [http://jquery.com/plugins/project/color official jQuery Color Animation plugin] dynamically and bind some color animations to occur once the new functionality is loaded.
$.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){ $("#go").click(function(){ $(".block").animate( { backgroundColor: 'pink' }, 1000) .animate( { backgroundColor: 'blue' }, 1000); }); });
HTML:
<button id="go">» Run</button> <div class="block"></div>
Example:
Load the test.js JavaScript file and execute it.
$.getScript("test.js");
Example:
Load the test.js JavaScript file and execute it, displaying an alert message when the execution is complete.
$.getScript("test.js", function(){ alert("Script loaded and executed."); });
-
jQuery.grep( Array array, Function callback, Boolean invert ) 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:
Filters the original array of numbers leaving that are not 5 and have an index greater than 3. Then it removes all 9s while inverting it.
var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ]; $("div").text(arr.join(", ")); arr = jQuery.grep(arr, function(n, i){ return (n != 5 && i > 4); }); $("p").text(arr.join(", ")); arr = jQuery.grep(arr, "a != 9"); $("span").text(arr.join(", "));
HTML:
<div></div> <p></p> <span></span>
Example:
Filter an array of numbers to include only numbers bigger then zero.
$.grep( [0,1,2], function(n,i){ return n > 0; });
Result:
[1, 2]
Example:
Filter an array of numbers to exclude numbers bigger then zero using the third parameter, invert.
$.grep( [0,1,2,3,4,5], "a > 1", true);
Result:
[0, 1]
-
jQuery.inArray( Any value, Array array ) returns Number
Determine the index of the first parameter in the Array (-1 if not found).
Example:
var arr = [ 4, "Pete", 8, "John" ]; $("span:eq(0)").text(jQuery.inArray("John", arr)); $("span:eq(1)").text(jQuery.inArray(4, arr)); $("span:eq(2)").text(jQuery.inArray("David", arr));
HTML:
<div>"John" found at <span></span></div> <div>4 found at <span></span></div> <div>"David" found at <span></span></div>
-
jQuery.isFunction( Object obj ) returns boolean
Determine if the parameter passed is a function.
Example:
Test a few parameter examples.
function stub() { } var objs = [ function () {}, { x:15, y:20 }, null, stub, "function" ]; jQuery.each(objs, function (i) { var isFunc = jQuery.isFunction(objs[i]); $("span:eq( " + i + ")").text(isFunc); });
HTML:
<div>jQuery.isFunction(objs[0]) = <span></span></div> <div>jQuery.isFunction(objs[1]) = <span></span></div> <div>jQuery.isFunction(objs[2]) = <span></span></div> <div>jQuery.isFunction(objs[3]) = <span></span></div> <div>jQuery.isFunction(objs[4]) = <span></span></div>
Example:
Finds out if the parameter is a funcion.
$.isFunction(function(){});
Result:
true
-
jQuery.makeArray( Object obj ) returns Array
Turns an array-like object into a true array.
Array-like objects have a length property and its properties are numbered from 0 to length - 1. Typically it will be unnecessary to use this function if you are using jQuery which uses this function internally.Example:
Turn a collection of HTMLElements into an Array of them.
var arr = jQuery.makeArray(document.getElementsByTagName("div")); arr.reverse(); // use an Array method on list of dom elements $(arr).appendTo(document.body);
HTML:
<div>First</div> <div>Second</div> <div>Third</div> <div>Fourth</div>
-
jQuery.map( Array array, Function callback ) returns Array
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.Example:
Maps the original array to a new one and adds 4 to each value.
var arr = [ "a", "b", "c", "d", "e" ] $("div").text(arr.join(", ")); arr = jQuery.map(arr, function(n, i){ return (n.toUpperCase() + i); }); $("p").text(arr.join(", ")); arr = jQuery.map(arr, "a + a"); $("span").text(arr.join(", "));
HTML:
<div></div> <p></p> <span></span>
Example:
Maps the original array to a new one and adds 4 to each value.
$.map( [0,1,2], function(n){ return n + 4; });
Result:
[4, 5, 6]
Example:
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(n){ return n > 0 ? n + 1 : null; });
Result:
[2, 3]
Example:
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(n){ return [ n, n + 1 ]; });
Result:
[0, 1, 1, 2, 2, 3]
Example:
Maps the original array to a new one, each element is squared.
$.map( [0,1,2,3], "a * a" );
Result:
[0, 1, 4, 9]
-
jQuery.noConflict( ) returns jQuery
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").Example:
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';
Example:
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 library
Example:
Creates a different alias instead of jQuery to use in the rest of the script.
var j = jQuery.noConflict(); // Do something with jQuery j("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';
-
jQuery.noConflict( Boolean extreme ) returns jQuery
Revert control of both the $ and jQuery variables to their original owners. '''Use with discretion.'''
This is a more-extreme version of the simple <a href='Core/jQuery.noConflict'>noConflict</a> method, as this one will completely undo what jQuery has introduced. This is to be used in an extreme case where you'd like to embed jQuery into a high-conflict environment. '''NOTE:''' It's very likely that plugins won't work after this particular method has been called.Example:
Completely move jQuery to a new namespace in another object.
var dom = {}; dom.query = jQuery.noConflict(true);
Result:
// Do something with the new jQuery dom.query("div p").hide(); // Do something with another library's $() $("content").style.display = 'none'; // Do something with another version of jQuery jQuery("div > p").hide();
-
jQuery.param( Array<Elements>, jQuery, Object obj ) returns String
Serializes an array of form elements or an object (core of <a href='Ajax/serialize'>.serialize()</a> method).
Example:
Serialize a key/value object.
var params = { width:1680, height:1050 }; var str = jQuery.param(params); $("#results").text(str);
HTML:
<div id="results"></div>
-
jQuery.post( String url, Map data, Function callback ) returns XMLHttpRequest
Load a remote page using an HTTP POST request.
This is an easy way to send a simple POST 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:
Request the test.php page, but ignore the return results.
$.post("test.php");
Example:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post("test.php", { name: "John", time: "2pm" } );
Example:
Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.post("test.php", function(data){ alert("Data Loaded: " + data); });
Example:
Alert out the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned).
$.post("test.cgi", { name: "John", time: "2pm" }, function(data){ alert("Data Loaded: " + data); });
-
jQuery.removeData( Element elem ) returns
Remove the expando attribute that allows data storage on an element.
This is the complement function to jQuery.data(elem) which is called as necessary by jQuery.data(elem, name, value).Example:
Set a data store then remove it.
var adiv = $("div").get(0); $("span:eq(0)").text("" + jQuery.data(adiv, "test1")); jQuery.data(adiv, "test1", "VALUE-1"); jQuery.data(adiv, "test2", "VALUE-2"); $("span:eq(1)").text("" + jQuery.data(adiv, "test1")); jQuery.removeData(adiv); $("span:eq(2)").text("" + jQuery.data(adiv, "test1")); $("span:eq(3)").text("" + jQuery.data(adiv, "test2"));
HTML:
<div>value1 before creation: <span></span></div> <div>value1 after creation: <span></span></div> <div>value1 after removal: <span></span></div> <div>value2 after removal: <span></span></div>
-
jQuery.removeData( Element elem, String name ) returns
Removes just this one named data store.
This is the complement function to jQuery.data(elem, name, value).Example:
Set a data store for 2 names then remove one of them.
var adiv = $("div").get(0); $("span:eq(0)").text("" + jQuery.data(adiv, "test1")); jQuery.data(adiv, "test1", "VALUE-1"); jQuery.data(adiv, "test2", "VALUE-2"); $("span:eq(1)").text("" + jQuery.data(adiv, "test1")); jQuery.removeData(adiv, "test1"); $("span:eq(2)").text("" + jQuery.data(adiv, "test1")); $("span:eq(3)").text("" + jQuery.data(adiv, "test2"));
HTML:
<div>value1 before creation: <span></span></div> <div>value1 after creation: <span></span></div> <div>value1 after removal: <span></span></div> <div>value2 after removal: <span></span></div>
-
jQuery.trim( String str ) returns String
Remove the whitespace from the beginning and end of a string.
Uses a regular expression to remove whitespace from the given string.Example:
Removes the two whitespaces at the start and at the end of the string.
$("button").click(function () { var str = " lots of spaces before and after "; alert("'" + str + "'"); str = jQuery.trim(str); alert("'" + str + "' - no longer"); });
HTML:
<button>Show Trim Example</button>
Example:
Removes the two whitespaces at the start and at the end of the string.
$.trim(" hello, how are you? ");
Result:
"hello, how are you?"
-
jQuery.unique( Array array ) returns Array
Remove all duplicate elements from an array of elements.
Example:
Removes any duplicate elements from the array of divs.
var divs = $("div").get(); // add 3 elements of class dup too (they are divs) divs = divs.concat($(".dup").get()); $("div:eq(1)").text("Pre-unique there are " + divs.length + " elements."); divs = jQuery.unique(divs); $("div:eq(2)").text("Post-unique there are " + divs.length + " elements.") .css("color", "red");
HTML:
<div>There are 6 divs in this document.</div> <div></div> <div class="dup"></div> <div class="dup"></div> <div class="dup"></div> <div></div>
Example:
Removes any duplicate elements from the array of divs.
$.unique(document.getElementsByTagName("div"));
Result:
[<div>, <div>, ...]
-
keydown( ) returns jQuery
Triggers the keydown event of each matched element.
This causes all of the functions that have been bound to the keydown event to be executed, and calls the browser's default keydown action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the keydown event. The keydown event usually fires when a key on the keyboard is pressed. -
keydown( Function fn ) returns jQuery
Bind a function to the keydown event of each matched element.
The keydown event fires when a key on the keyboard is pressed.Example:
To perform actions in response to keyboard presses on a page, try:
$(window).keydown(function(event){ switch (event.keyCode) { // ... // different keys do different things // Different browsers provide different codes // see here for details: http://unixpapa.com/js/key.html // ... } });
-
keypress( ) returns jQuery
Triggers the keypress event of each matched element.
This causes all of the functions that have been bound to the keypress event to be executed, and calls the browser's default keypress action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the keypress event. The keypress event usually fires when a key on the keyboard is pressed.
-
keypress( Function fn ) returns jQuery
Binds a function to the keypress event of each matched element.
The keypress event fires when a key on the keyboard is "clicked". A keypress is defined as a keydown and keyup on the same key. The sequence of these events is: <ul><li>keydown</li><li>keyup</li><li>keypress</li></ul>Example:
Show spaces and letters when typed.
$("input").keypress(function (e) { if (e.which == 32 || (65 <= e.which && e.which <= 65 + 25) || (97 <= e.which && e.which <= 97 + 25)) { var c = String.fromCharCode(e.which); $("p").append($("<span/>")) .children(":last") .append(document.createTextNode(c)); } else if (e.which == 8) { // backspace in IE only be on keydown $("p").children(":last").remove(); } $("div").text(e.which); });
HTML:
<input type="text" /> <p>Add text - </p> <div></div>
-
keyup( ) returns jQuery
Triggers the keyup event of each matched element.
This causes all of the functions that have been bound to the keyup event to be executed, and calls the browser's default keyup action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the keyup event. The keyup event usually fires when a key on the keyboard is released. -
keyup( Function fn ) returns jQuery
Bind a function to the keyup event of each matched element.
The keyup event fires when a key on the keyboard is released.Example:
To perform an action when the escape key has been released:
$(document).keyup(function(event){ if (event.keyCode == 27) { alert('escaped!'); } });
-
last( ) returns Element
Matches the last selected element.
Example:
Finds the last table row.
$("tr:last").css({backgroundColor: 'yellow', fontWeight: 'bolder'});
HTML:
<table> <tr><td>First Row</td></tr> <tr><td>Middle Row</td></tr> <tr><td>Last Row</td></tr> </table>
-
lastChild( ) returns Array<Element>
Matches the last child of its parent.
While <a href='Selectors/last'>:last</a> matches only a single element, this matches more then one: One for each parent.Example:
Finds the last span in each matched div and adds some css plus a hover state.
$("div span:last-child") .css({color:"red", fontSize:"80%"}) .hover(function () { $(this).addClass("solast"); }, function () { $(this).removeClass("solast"); });
HTML:
<div> <span>John,</span> <span>Karl,</span> <span>Brandon,</span> <span>Sam</span> </div> <div> <span>Glen,</span> <span>Tane,</span> <span>Ralph,</span> <span>David</span> </div>
-
length returns Number
The number of elements in the jQuery object.
In a The number of elements currently matched. The <a href='Core/size'>size</a> function will return the same value.Example:
Count the divs. Click to add more.
$(document.body).click(function () { $(document.body).append($("<div>")); var n = $("div").length; $("span").text("There are " + n + " divs." + "Click to add more."); }).trigger('click'); // trigger the click to start
HTML:
<span></span> <div></div>
-
load( String url, Map data, Callback callback ) returns jQuery
Load HTML from a remote file and inject it into the DOM.
A GET request will be performed by default - but if you pass in any extra parameters then a POST will occur.
In jQuery 1.2 you can now specify a jQuery selector in the URL. Doing so will filter the incoming HTML document, only injecting the elements that match the selector. The syntax looks something like "url #some > selector". See the examples for more information.Example:
Load a piece of the documentation sidebar navigation into a custom unordered list.
$("#links").load("/Main_Page #p-Getting-Started li");
HTML:
<b>jQuery Links:</b> <ul id="links"></ul>
Example:
Load the feeds.html file into the div with the ID of feeds.
$("#feeds").load("feeds.html");
Result:
<div id="feeds"><b>45</b> feeds found.</div>
Example:
Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding.
$("#feeds").load("feeds.php", {limit: 25}, function(){ alert("The last 25 entries in the feed have been loaded"); });
-
load ( Function fn ) returns jQuery
Binds a function to the load event of each matched element.
When bound to the window element, the event fires when the user agent finishes loading all content within a document, including window, frames, objects and images. For elements, it fires when the target element and all of its content has finished loading.Example:
Run a function when the page is fully loaded including graphics.
$(window).load(function () { // run code });
-
lt( Number index ) returns Array<Element>
Matches all elements with an index below the given one.
Example:
Finds TDs less than the one with the 4th index (TD#4).
$("td:lt(4)").css("color", "red");
HTML:
<table border="1"> <tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr> <tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr> <tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr> </table>
-
map( Function callback ) returns jQuery
Translate a set of elements in the jQuery object into another set of values in an array (which may, or may not, be elements).
You could use this to build lists of values, attributes, css values - or even perform special, custom, selector transformations.
This is provided as a convenience method for using <a href='Utilities/jQuery.map'>$.map()</a>.Example:
Build a list of all the values within a form.
$("p").append( $("input").map(function(){ return $(this).val(); }).get().join(", ") );
HTML:
<p><b>Values: </b></p> <form> <input type="text" name="name" value="John"/> <input type="text" name="password" value="password"/> <input type="text" name="url" value="http://ejohn.org/"/> </form>
Example:
A contrived example to show some functionality.
var mappedItems = $("li").map(function (index) { var replacement = $("<li>").text($(this).text()).get(0); if (index == 0) { // make the first item all caps $(replacement).text($(replacement).text().toUpperCase()); } else if (index == 1 || index == 3) { // delete the second and fourth items replacement = null; } else if (index == 2) { // make two of the third item and add some text replacement = [replacement,$("<li>").get(0)]; $(replacement[0]).append("<b> - A</b>"); $(replacement[1]).append("Extra <b> - B</b>"); } // replacment will be an dom element, null, // or an array of dom elements return replacement; }); $("#results").append(mappedItems);
HTML:
<ul> <li>First</li> <li>Second</li> <li>Third</li> <li>Fourth</li> <li>Fifth</li> </ul> <ul id="results"> </ul>
-
mousedown ( Function fn ) returns jQuery
Binds a function to the mousedown event of each matched element.
The mousedown event fires when the pointing device button is pressed over an element. -
mousemove( Function fn ) returns jQuery
Bind a function to the mousemove event of each matched element.
The mousemove event fires when the pointing device is moved while it is over an element. The event handler is passed one variable - the event object. Its .clientX and .clientY properties represent the coordinates of the mouse.Example:
Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window which in this case is the iframe.
$("div").mousemove(function(e){ var pageCoords = "( " + e.pageX + ", " + e.pageY + " )"; var clientCoords = "( " + e.clientX + ", " + e.clientY + " )"; $("span:first").text("( e.pageX, e.pageY ) - " + pageCoords); $("span:last").text("( e.clientX, e.clientY ) - " + clientCoords); });
HTML:
<p> Try scrolling too. <span>Move the mouse over the div.</span> <span> </span> </p> <div></div>
-
mouseout( Function fn ) returns jQuery
Bind a function to the mouseout event of each matched element.
The mouseout event fires when the pointing device is moved away from an element. -
mouseover( Function fn ) returns jQuery
Bind a function to the mouseover event of each matched element.
The mouseout event fires when the pointing device is moved onto an element. -
mouseup( Function fn ) returns jQuery
Bind a function to the mouseup event of each matched element.
The mouseup event fires when the pointing device button is released over an element. -
multiple( Selector selector1, Selector selector2, Selector selectorN ) returns Array<Element>
Matches the combined results of all the specified selectors.
You can specify any number of selectors to combine into a single result. Note order of the dom elements in the jQuery object aren't necessarily identical.Example:
Finds the elements that match any of these three selectors.
$("div,span,p.myClass").css("border","3px solid red");
HTML:
<div>div</div> <p class="myClass">p class="myClass"</p> <p class="notMyClass">p class="notMyClass"</p> <span>span</span>
Example:
Show the order in the jQuery object.
var list = $("div,p,span").map(function () { return this.tagName; }).get().join(", "); $("b").append(document.createTextNode(list));
HTML:
<span>span</span> <p>p</p> <p>p</p> <div>div</div> <span>span</span> <p>p</p> <div>div</div> <b></b>
-
next( String expr ) returns jQuery
Get a set of elements containing the unique next siblings of each of the given set of elements.
next only returns the very next sibling for each element, not all next siblings (see nextAll).
You may provide an optional expression to filter the returned set.Example:
Find the very next sibling of each disabled button and change its text "this button is disabled".
$("button[disabled]").next().text("this button is disabled");
HTML:
<div><button disabled="disabled">First</button> - <span></span></div> <div><button>Second</button> - <span></span></div> <div><button disabled="disabled">Third</button> - <span></span></div>
Example:
Find the very next sibling of each paragraph that has a class "selected".
$("p").next(".selected").css("background", "yellow");
HTML:
<p>Hello</p> <p class="selected">Hello Again</p> <div><span>And Again</span></div>
-
next( Selector prev, Selector next ) returns Array<Element>
Matches all next elements specified by "next" that are next to elements specified by "prev".
Example:
Finds all inputs that are next to a label.
$("label + input").css("color", "blue").val("Labeled!")
HTML:
<form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" />
-
nextAll( String expr ) returns jQuery
Find all sibling elements after the current element.
Use an optional expression to filter the matched set.Example:
Locate all the divs after the first and give them a class.
$("div:first").nextAll().addClass("after");
HTML:
<div></div> <div></div> <div></div> <div></div>
Example:
Locate all the paragraphs after the second child in the body and give them a class.
$(":nth-child(1)").nextAll("p").addClass("after");
HTML:
<p>p</p> <div>div</div> <p>p</p> <p>p</p> <div>div</div> <p>p</p> <div>div</div>
-
not( Selector selector ) returns Array<Element>
Filters out all elements matching the given selector.
Example:
Finds all inputs that are not checked and hilites the next sibling span. Notice there is no change when clicking the checkboxes since no click events have been linked.
$("input:not(:checked) + span").css("background-color", "yellow"); $("input").attr("disabled", "disabled");
HTML:
<div> <input type="checkbox" name="a" /> <span>Mary</span> </div> <div> <input type="checkbox" name="b" /> <span>Paul</span> </div> <div> <input type="checkbox" name="c" checked="checked" /> <span>Peter</span> </div>
-
not( String, DOMElement, Array<DOMElement> expr ) returns jQuery
Removes elements matching the specified expression from the set of matched elements.
Example:
Adds a border to divs that are not green or blue.
$("div").not(".green, #blueone") .css("border-color", "red");
HTML:
<div></div> <div id="blueone"></div> <div></div> <div class="green"></div> <div class="green"></div> <div class="gray"></div> <div></div>
Example:
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not( $("#selected")[0] )
Example:
Removes the element with the ID "selected" from the set of all paragraphs.
$("p").not("#selected")
Example:
Removes all elements that match "div p.selected" from the total set of all paragraphs.
$("p").not($("div p.selected"))
-
nthChild( Number/String index ) returns Array<Element>
Matches the nth-child of its parent or all its even or odd children.
While <a href='Selectors/eq'>:eq(index)</a> matches only a single element, this matches more then one: One for each parent with index. Multiple for each parent with even, odd, or equation.
The specified index is one-indexed, in contrast to :eq() which starts at zero.Example:
Finds the second li in each matched ul and notes it.
$("ul li:nth-child(2)").append("<span> - 2nd!</span>");
HTML:
<div><ul> <li>John</li> <li>Karl</li> <li>Brandon</li> </ul></div> <div><ul> <li>Sam</li> </ul></div> <div><ul> <li>Glen</li> <li>Tane</li> <li>Ralph</li> <li>David</li> </ul></div>
Example:
This is a playground to see how the selector works with different strings. Notice that this is different from the :even and :odd which have no regard for parent and just filter the list of elements to every other one. The :nth-child, however, counts the index of the child to its particular parent. In any case, it's easier to see than explain so...
$("button").click(function () { var str = $(this).text(); $("tr").css("background", "white"); $("tr" + str).css("background", "#e2e1fb"); $("#inner").text(str); });
HTML:
<div> <button>:nth-child(even)</button> <button>:nth-child(odd)</button> <button>:nth-child(3n)</button> <button>:nth-child(2)</button> </div> <div> <button>:nth-child(3n+1)</button> <button>:nth-child(3n+2)</button> <button>:even</button> <button>:odd</button> </div> <div><table> <tr><td>John</td></tr> <tr><td>Karl</td></tr> <tr><td>Brandon</td></tr> <tr><td>Benjamin</td></tr> </table></div> <div><table> <tr><td>Sam</td></tr> </table></div> <div><table> <tr><td>Glen</td></tr> <tr><td>Tane</td></tr> <tr><td>Ralph</td></tr> <tr><td>David</td></tr> <tr><td>Mike</td></tr> <tr><td>Dan</td></tr> </table></div> <span> tr<span id="inner"></span> </span>
-
odd( ) returns Array<Element>
Matches odd elements, zero-indexed.
Example:
Finds odd table rows, matching the second, fourth and so on (index 1, 3, 5 etc.).
$("tr:odd").css("background-color", "#bbbbff");
HTML:
<table border="1"> <tr><td>Row with Index #0</td></tr> <tr><td>Row with Index #1</td></tr> <tr><td>Row with Index #2</td></tr> <tr><td>Row with Index #3</td></tr> </table>
-
offset( ) returns Object{top,left}
Get the current offset of the first matched element relative to the viewport.
The returned object contains two <a href='Types#Integer'>Integer</a> properties, top and left. The method works only with visible elements.Example:
Access the offset of the second paragraph:
var p = $("p:last"); var offset = p.offset(); p.html( "left: " + offset.left + ", top: " + offset.top );
HTML:
<p>Hello</p><p>2nd Paragraph</p>
Example:
Click to see the offset.
$("*", document.body).click(function (e) { var offset = $(this).offset(); e.stopPropagation(); $("#result").text(this.tagName + " coords ( " + offset.left + ", " + offset.top + " )"); });
HTML:
<div id="result">Click an element.</div> <p> This is the best way to <span>find</span> an offset. </p> <div class="abs"> </dov>
-
one( String type, Object data, Function fn ) returns jQuery
Binds a handler to a particular event to be executed <i>once</i> for each matched element.
<p>The handler is executed only once for each element. Otherwise, the same rules as described in <a href='Events/bind'>bind</a>() 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 should return false.</p><p>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.</p>Example:
Tie a one-time click to each div.
var n = 0; $("div").one("click", function(){ var index = $("div").index(this); $(this).css({ borderStyle:"inset", cursor:"auto" }); $("p").text("Div at index #" + index + " clicked." + " That's " + ++n + " total clicks."); });
HTML:
<div></div> <div></div> <div></div> <div></div> <div></div> <p>Click a green square...</p>
Example:
To display the text of all paragraphs in an alert box the first time each of them is clicked:
$("p").one("click", function(){ alert( $(this).text() ); });
-
onlyChild( ) returns Array<Element>
Matches the only child of its parent.
If the parent has other child elements, nothing is matched.Example:
Finds the button with no siblings in each matched div and modifies look.
$("div button:only-child").text("Alone").css("border", "2px blue solid");
HTML:
<div> <button>Sibling!</button> <button>Sibling!</button> </div> <div> <button>Sibling!</button> </div> <div> None </div> <div> <button>Sibling!</button> <button>Sibling!</button> <button>Sibling!</button> </div> <div> <button>Sibling!</button> </div>
Result:
[ <li>Glen</li> ]
-
parent( ) returns Array<Element>
Matches all elements that are parents - they have child elements, including text.
Example:
Finds all tds with children, including text.
$("td:parent").fadeTo(1500, 0.3);
HTML:
<table border="1"> <tr><td>Value 1</td><td></td></tr> <tr><td>Value 2</td><td></td></tr> </table>
-
parent( String expr ) returns jQuery
Get a set of elements containing the unique parents of the matched set of elements.
You may use an optional expression to filter the set of parent elements that will match.Example:
Shows the parent of each element as (parent > child). Check the View Source to see the raw html.
$("*", document.body).each(function () { var parentTag = $(this).parent().get(0).tagName; $(this).prepend(document.createTextNode(parentTag + " > ")); });
HTML:
<div>div, <span>span, </span> <b>b </b> </div> <p>p, <span>span, <em>em </em> </span> </p> <div>div, <strong>strong, <span>span, </span> <em>em, <b>b, </b> </em> </strong> <b>b </b> </div>
Example:
Find the parent element of each paragraph with a class "selected".
$("p").parent(".selected").css("background", "yellow");
HTML:
<div><p>Hello</p></div> <div class="selected"><p>Hello Again</p></div>
-
parents( String expr ) returns jQuery
Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
The matched elements can be filtered with an optional expression.
Example:
Find all parent elements of each span.
var parentEls = $("b").parents() .map(function () { return this.tagName; }) .get().join(", "); $("b").append("<strong>" + parentEls + "</strong>");
HTML:
<div> <p> <span> <b>My parents are: </b> </span> </p> </div>
Example:
Click to find all unique div parent elements of each span.
function showParents() { $("div").css("border-color", "white"); var len = $("span.selected") .parents("div") .css("border", "2px red solid") .length; $("b").text("Unique div parents: " + len); } $("span").click(function () { $(this).toggleClass("selected"); showParents(); });
HTML:
<p> <div> <div><span>Hello</span></div> <span>Hello Again</span> </div> <div> <span>And Hello Again</span> </div> </p> <b>Click Hellos to toggle their parents.</b>
-
password( ) returns Array<Element>
Matches all input elements of type password.
Example:
Finds all password inputs.
var input = $(":password").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
prepend( String, Element, jQuery content ) returns jQuery
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.Example:
Prepends some HTML to all paragraphs.
$("p").prepend("<b>Hello </b>");
HTML:
<p>there friend!</p> <p>amigo!</p>
Example:
Prepends a DOM Element to all paragraphs.
$("p").prepend(document.createTextNode("Hello "));
HTML:
<p>is what I'd say</p> <p>is what I said</p>
Example:
Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs.
$("p").prepend( $("b") );
HTML:
<p> is what was said.</p><b>Hello</b>
-
prependTo( String content ) returns jQuery
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.Example:
Prepends all spans to the element with the ID "foo"
$("span").prependTo("#foo"); // check prepend() examples
HTML:
<div id="foo">FOO!</div> <span>I have something to say... </span>
-
prev( String expr ) returns jQuery
Get a set of elements containing the unique previous siblings of each of the matched set of elements.
Use an optional expression to filter the matched set.
Only the immediately previous sibling is returned, not all previous siblings.Example:
Find the very previous sibling of each div.
var $curr = $("#start"); $curr.css("background", "#f99"); $("button").click(function () { $curr = $curr.prev(); $("div").css("background", ""); $curr.css("background", "#f99"); });
HTML:
<div></div> <div></div> <div><span>has child</span></div> <div></div> <div></div> <div></div> <div id="start"></div> <div></div> <p><button>Go to Prev</button></p>
Example:
Find the very previous sibling of each paragraph that has a class "selected".
$("p").prev(".selected").css("background", "yellow");
HTML:
<div><span>Hello</span></div> <p class="selected">Hello Again</p> <p>And Again</p>
-
prevAll( String expr ) returns jQuery
Find all sibling elements before the current element.
Use an optional expression to filter the matched set.Example:
Locate all the divs before the last and give them a class.
$("div:last").prevAll().addClass("before");
HTML:
<div></div> <div></div> <div></div> <div></div>
-
queue( ) returns Array<Function>
Returns a reference to the first element's queue (which is an array of functions).
Example:
Show the length of the queue.
$("#show").click(function () { var n = $("div").queue("fx"); $("span").text("Queue length is: " + n.length); }); function runIt() { $("div").show("slow"); $("div").animate({left:'+=200'},2000); $("div").slideToggle(1000); $("div").slideToggle("fast"); $("div").animate({left:'-=200'},1500); $("div").hide("slow"); $("div").show(1200); $("div").slideUp("normal", runIt); } runIt();
HTML:
<button id="show">Show Length of Queue</button> <span></span> <div></div>
-
queue( Function callback ) returns jQuery
Adds a new function, to be executed, onto the end of the queue of all matched elements.
Example:
Queue a custom function.
$(document.body).click(function () { $("div").show("slow"); $("div").animate({left:'+=200'},2000); $("div").queue(function () { $(this).addClass("newcolor"); $(this).dequeue(); }); $("div").animate({left:'-=200'},500); $("div").queue(function () { $(this).removeClass("newcolor"); $(this).dequeue(); }); $("div").slideUp(); });
HTML:
Click here... <div></div>
-
queue( Array<Function> queue ) returns jQuery
Replaces the queue of all matched element with this new queue (the array of functions).
Example:
Set a queue array to delete the queue.
$("#start").click(function () { $("div").show("slow"); $("div").animate({left:'+=200'},5000); $("div").queue(function () { $(this).addClass("newcolor"); $(this).dequeue(); }); $("div").animate({left:'-=200'},1500); $("div").queue(function () { $(this).removeClass("newcolor"); $(this).dequeue(); }); $("div").slideUp(); }); $("#stop").click(function () { $("div").queue("fx", []); $("div").stop(); });
HTML:
<button id="start">Start</button> <button id="stop">Stop</button> <div></div>
-
radio( ) returns Array<Element>
Matches all input elements of type radio.
Example:
Finds all radio inputs.
var input = $(":radio").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" name="asdf" /> <input type="radio" name="asdf" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
ready( Function fn ) returns jQuery
Binds a function to be executed whenever the DOM is ready to be traversed and manipulated.
<p>This is probably the most important function included in the event module, as it can greatly improve the response times of your web applications.</p><p>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 when what 99.99% of all JavaScript code needs to run.</p><p>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 risk of naming collisions.</p><p>Please ensure you have no code in your <body> onload event handler, otherwise $(document).ready() may not fire.</p><p>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.</p>Example:
Display a message when the DOM is loaded.
$("p").text("The DOM is now loaded and can be manipulated.");
HTML:
<p> </p>
Example:
To run code when the DOM loads, write:
$(document).ready(function(){ // Your code here... });
Example:
To use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias, write:
jQuery(function($) { // Your code using failsafe $ alias here... });
Example:
Commonly written as:
$(function() { // Your code here... });
-
remove( String expr ) returns jQuery
Removes all matched elements from the DOM.
This does NOT remove them from the jQuery object, allowing you to use the matched elements further. Note that this function starting with 1.2.2 will also remove all event handlers and internally cached data. So:
<code> $("#foo").remove().appendTo("#bar"); </code>
should be written as
<code> $("#foo").appendTo("#bar"); </code>
to avoid losing the event handlers.
Can be filtered with an optional expression.Example:
Removes all paragraphs from the DOM
$("button").click(function () { $("p").remove(); });
HTML:
<p>Hello</p> how are <p>you?</p> <button>Call remove() on paragraphs
Example:
Removes all paragraphs that contain "Hello" from the DOM
$("button").click(function () { $("p").remove(":contains('Hello')"); });
HTML:
<p class="hello">Hello</p> how are <p>you?</p> <button>Call remove(":contains('Hello')") on paragraphs
-
removeAttr( String name ) returns jQuery
Remove an attribute from each of the matched elements.
Example:
Clicking the button enables the input next to it.
$("button").click(function () { $(this).next().removeAttr("disabled") .focus() .val("editable now"); });
HTML:
<button>Enable</button> <input type="text" disabled="disabled" value="can't edit this" />
-
removeClass( String ''(optional)'' class ) returns jQuery
Removes all or the specified class(es) from the set of matched elements.
Example:
Remove the class 'blue' from the matched elements.
$("p:even").removeClass("blue");
HTML:
<p class="blue under">Hello</p> <p class="blue under highlight">and</p> <p class="blue under">then</p> <p class="blue under">Goodbye</p>
Example:
Remove the class 'blue' and 'under' from the matched elements.
$("p:odd").removeClass("blue under");
HTML:
<p class="blue under">Hello</p> <p class="blue under highlight">and</p> <p class="blue under">then</p> <p class="blue under">Goodbye</p>
Example:
Remove all the classes from the matched elements.
$("p:eq(1)").removeClass();
HTML:
<p class="blue under">Hello</p> <p class="blue under highlight">and</p> <p class="blue under">then</p> <p class="blue under">Goodbye</p>
-
replaceAll( Selector selector ) returns jQuery
Replaces the elements matched by the specified selector with the matched elements.
This function is the complement to replaceWith() which does the same task with the parameters reversed.Example:
Replace all the paragraphs with bold words.
$("<b>Paragraph. </b>").replaceAll("p"); // check replaceWith() examples
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
-
replaceWith( String, Element, jQuery content ) returns jQuery
Replaces all matched elements with the specified HTML or DOM elements.
Example:
On click, replace the button with a div containing the same word.
$("button").click(function () { $(this).replaceWith("<div>" + $(this).text() + "</div>"); });
HTML:
<button>First</button> <button>Second</button> <button>Third</button>
Example:
Replace all the paragraphs with bold words.
$("p").replaceWith("<b>Paragraph. </b>");
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
Example:
Replace all the paragraphs with empty div elements.
$("p").replaceWith(document.createElement("div"));
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
Example:
On click, replace each paragraph with a jQuery div object that is already in the DOM. Notice it doesn't clone the object but rather moves it to replace the paragraph.
$("p").click(function () { $(this).replaceWith($("div")); });
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p> <div>Replaced!</div>
-
reset( ) returns Array<Element>
Matches all input elements of type reset.
Example:
Finds all reset inputs.
var input = $(":reset").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
resize( Function fn ) returns jQuery
Bind a function to the resize event of each matched element.
The resize event fires when a document view is resizedExample:
To make resizing the web page window a pain in the neck, try:
$(window).resize(function(){ alert("Stop it!"); });
-
scroll( Function fn ) returns jQuery
Bind a function to the scroll event of each matched element.
The scroll event fires when a document view is scrolled.Example:
To do something when your page is scrolled:
$("p").clone().appendTo(document.body); $("p").clone().appendTo(document.body); $("p").clone().appendTo(document.body); $(window).scroll(function () { $("span").css("display", "inline").fadeOut("slow"); });
HTML:
<div>Try scrolling the iframe.</div> <p>Paragraph - <span>Scroll happened!</span></p>
-
select( ) returns jQuery
Trigger the select event of each matched element.
This causes all of the functions that have been bound to that select event to be executed, and calls the browser's default select action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the select event.Example:
To trigger the select event on all input elements, try:
$("input").select();
-
select( Function fn ) returns jQuery
Bind a function to the select event of each matched element.
The select event fires when a user selects some text in a text field, including input and textarea.Example:
To do something when text in input boxes is selected:
$(document).select( function () { $("div").text("Something was selected").show().fadeOut(1000); });
HTML:
<p> Click and drag the mouse to select text in the inputs. </p> <input type="text" value="Some text" /> <input type="text" value="to test on" /> <div></div>
-
selected( ) returns Array<Element>
Matches all elements that are selected.
Example:
Attaches a change even to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
$("select").change(function () { var str = ""; $("select option:selected").each(function () { str += $(this).text() + " "; }); $("div").text(str); }) .trigger('change');
HTML:
<select name="garden" multiple="multiple"> <option>Flowers</option> <option selected="selected">Shrubs</option> <option>Trees</option> <option selected="selected">Bushes</option> <option>Grass</option> <option>Dirt</option> </select> <div></div>
-
serialize( ) returns jQuery
Serializes a set of input elements into a string of data. This will serialize all given elements.
As of jQuery 1.2 the serialize method correctly serializes forms. For older versions of jQuery, the [http://www.malsup.com/jquery/form/ Form Plugin's] fieldSerialize method should be used.Example:
Serialize a form to a query string, that could be sent to a server in an Ajax request.
function showValues() { var str = $("form").serialize(); $("#results").text(str); } $(":checkbox, :radio").click(showValues); $("select").change(showValues); showValues();
HTML:
<form> <select name="single"> <option>Single</option> <option>Single2</option> </select> <select name="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" name="check" value="check1"/> check1 <input type="checkbox" name="check" value="check2" checked="checked"/> check2 <input type="radio" name="radio" value="radio1" checked="checked"/> radio1 <input type="radio" name="radio" value="radio2"/> radio2 </form> <p><tt id="results"></tt></p>
-
serializeArray( ) returns jQuery
Serializes all forms and form elements (like the <a href='Ajax/serialize'>.serialize()</a> method) but returns a JSON data structure for you to work with.
Example:
Get the values from a form, iterate through them, and append them to a results display.
function showValues() { var fields = $(":input").serializeArray(); $("#results").empty(); jQuery.each(fields, function(i, field){ $("#results").append(field.value + " "); }); } $(":checkbox, :radio").click(showValues); $("select").change(showValues); showValues();
HTML:
<p><b>Results:</b> <span id="results"></span></p> <form> <select name="single"> <option>Single</option> <option>Single2</option> </select> <select name="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" name="check" value="check1"/> check1 <input type="checkbox" name="check" value="check2" checked="checked"/> check2 <input type="radio" name="radio" value="radio1" checked="checked"/> radio1 <input type="radio" name="radio" value="radio2"/> radio2 </form>
-
show( ) returns jQuery
Displays each of the set of matched elements if they are hidden.
Same as <a href='Effects/show#speedcallback'>show( speed, [callback] )</a> without animations. Doesn't change anything if the selected elements are all visible. It doesn't matter if the element is hidden via a hide() call, or via a display:none in a stylesheet.Example:
Shows all paragraphs.
$("p").show()
HTML:
<p style="display:none">Hello</p>
-
show( String, Number speed, Function callback ) returns jQuery
Show 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:
Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds.
$("button").click(function () { $("p").show("slow"); });
HTML:
<button>Show it</button> <p style="display: none">Hello</p>
Example:
Animates all hidden divs to show fastly in order, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one.
$("#showr").click(function () { $("div:eq(0)").show("fast", function () { // use callee so don't have to name the function $(this).next().show("fast", arguments.callee); }); }); $("#hidr").click(function () { $("div").hide(2000); });
HTML:
<button id="showr">Show</button> <button id="hidr">Hide</button> <div>Hello,</div> <div>how</div> <div>are</div> <div>you?</div>
Example:
Animates all span and input elements to show normally. Once the animation is done, it changes the text.
function doIt() { $("span,div").show("normal"); } $("button").click(doIt); // can pass in function name $("form").submit(function () { if ($("input").val() == "yes") { $("p").show(4000, function () { $(this).text("Ok, DONE! (now showing)"); }); } $("span,div").hide("normal"); return false; // to stop the submit });
HTML:
<button>Do it!</button> <span>Are you sure? (type 'yes' if you are) </span> <div> <form> <input type="text" /> </form> </div> <p style="display:none;">I'm hidden...</p>
-
siblings( String expr ) returns jQuery
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.
Example:
Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate).
var len = $(".hilite").siblings() .css("color", "red") .length; $("b").text(len);
HTML:
<ul> <li>One</li> <li>Two</li> <li class="hilite">Three</li> <li>Four</li> </ul> <ul> <li>Five</li> <li>Six</li> <li>Seven</li> </ul> <ul> <li>Eight</li> <li class="hilite">Nine</li> <li>Ten</li> <li class="hilite">Eleven</li> </ul> <p>Unique siblings: <b></b></p>
Example:
Find all siblings with a class "selected" of each div.
$("p").siblings(".selected").css("background", "yellow");
HTML:
<div><span>Hello</span></div> <p class="selected">Hello Again</p> <p>And Again</p>
-
siblings( Selector prev, Selector siblings ) returns Array<Element>
Matches all sibling elements after the "prev" element that match the filtering "siblings" selector.
Example:
Finds all divs that are siblings after the element with #prev as its id. Notice the span isn't selected since it is not a div and the "niece" isn't selected since it is a child of a sibling, not an actual sibling.
$("#prev ~ div").css("border", "3px groove blue");
HTML:
<div>div (doesn't match since before #prev)</div> <div id="prev">div#prev</div> <div>div sibling</div> <div>div sibling <div id="small">div neice</div></div> <span>span sibling (not div)</span> <div>div sibling</div>
-
size( ) returns Number
The number of elements in the jQuery object.
This returns the same number as the '<a href='Core/length'>length</a>' property of the jQuery object.Example:
Count the divs. Click to add more.
$(document.body).click(function () { $(document.body).append($("<div>")); var n = $("div").size(); $("span").text("There are " + n + " divs." + "Click to add more."); }).click(); // trigger the click to start
HTML:
<span></span> <div></div>
-
slice( Integer start, Integer end ) returns jQuery
Selects a subset of the matched elements.
Behaves exactly like the built-in Array slice method.Example:
Turns divs yellow based on a random slice.
function colorEm() { var $div = $("div"); var start = Math.floor(Math.random() * $div.length); var end = Math.floor(Math.random() * ($div.length - start)) + start + 1; if (end == $div.length) end = undefined; $div.css("background", ""); if (end) $div.slice(start, end).css("background", "yellow"); else $div.slice(start).css("background", "yellow"); $("span").text('$("div").slice(' + start + (end ? ', ' + end : '') + ').css("background", "yellow");'); } $("button").click(colorEm);
HTML:
<button>Turn slice yellow</button> <span>Click the button!</span> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div>
Example:
Selects all paragraphs, then slices the selection to include only the first element.
$("p").slice(0, 1).wrapInner("<b></b>");
Example:
Selects all paragraphs, then slices the selection to include only the first and second element.
$("p").slice(0, 2).wrapInner("<b></b>");
Example:
Selects all paragraphs, then slices the selection to include only the second element.
$("p").slice(1, 2).wrapInner("<b></b>");
Example:
Selects all paragraphs, then slices the selection to include only the second and third element.
$("p").slice(1).wrapInner("<b></b>");
Example:
Selects all paragraphs, then slices the selection to include only the third element.
$("p").slice(-1).wrapInner("<b></b>");
-
slideDown( String, Number speed, Function callback ) returns jQuery
Reveal all matched elements by adjusting their height and firing an optional callback after completion.
Only the height is adjusted for this animation, causing all matched elements to be revealed in a "sliding" manner.Example:
Animates all divs to slide down and show themselves over 600 milliseconds.
$(document.body).click(function () { if ($("div:first").is(":hidden")) { $("div").slideDown("slow"); } else { $("div").hide(); } });
HTML:
Click me! <div></div> <div></div> <div></div>
Example:
Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus.
$("div").click(function () { $(this).css({ borderStyle:"inset", cursor:"wait" }); $("input").slideDown(1000,function(){ $(this).css("border", "2px red inset") .filter(".middle") .css("background", "yellow") .focus(); $("div").css("visibility", "hidden"); }); });
HTML:
<div>Push!</div> <input type="text" /> <input type="text" class="middle" /> <input type="text" />
-
slideToggle( String, Number speed, Function callback ) returns jQuery
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
Only the height is adjusted for this animation, causing all matched elements to be hidden or shown in a "sliding" manner.Example:
Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds.
$("button").click(function () { $("p").slideToggle("slow"); });
HTML:
<button>Toggle</button> <p> This is the paragraph to end all paragraphs. You should feel <em>lucky</em> to have seen such a paragraph in your life. Congratulations! </p>
Example:
Animates divs between dividers with a toggle that makes some appear and some disappear.
$("button").click(function () { $("div:not(.still)").slideToggle("slow", function () { var n = parseInt($("span").text(), 10); $("span").text(n + 1); }); });
HTML:
<button>Toggle</button> There have been <span>0</span> toggled divs. <div></div><div class="still"></div> <div style="display:none;"></div><div class="still"></div> <div></div><div class="still"></div> <div class="hider"></div><div class="still"></div> <div class="hider"></div><div class="still"></div> <div></div>
-
slideUp( String, Number speed, Function callback ) returns jQuery
Hide all matched elements by adjusting their height and firing an optional callback after completion.
Only the height is adjusted for this animation, causing all matched elements to be hidden in a "sliding" manner.Example:
Animates all divs to slide up, completing the animation within 400 milliseconds.
$(document.body).click(function () { if ($("div:first").is(":hidden")) { $("div").show("fast"); } else { $("div").slideUp(); } });
HTML:
Click me! <div></div> <div></div> <div></div> <div></div> <div></div>
Example:
Animates all paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert.
$("button").click(function () { $(this).parent().slideUp("slow", function () { $("#msg").text($("button", this).text() + " has completed."); }); });
HTML:
<div> <button>Hide One</button> <input type="text" value="One" /> </div> <div> <button>Hide Two</button> <input type="text" value="Two" /> </div> <div> <button>Hide Three</button> <input type="text" value="Three" /> </div> <div id="msg"></div>
-
stop( ) returns jQuery
Stops all the currently running animations on all the specified elements.
If any animations are queued to run, then they will begin immediately.Example:
Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one.
// Start animation $("#go").click(function(){ $(".block").animate({left: '+=100px'}, 2000); }); // Stop animation when button is clicked $("#stop").click(function(){ $(".block").stop(); }); // Start animation in the opposite direction $("#back").click(function(){ $(".block").animate({left: '-=100px'}, 2000); });
HTML:
<button id="go">Go</button> <button id="stop">STOP!</button> <button id="back">Back</button> <div class="block"></div>
-
submit( ) returns Array<Element>
Matches all input elements of type submit.
Example:
Finds all submit inputs.
var input = $(":submit").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
submit( ) returns jQuery
Trigger the submit event of each matched element.
This causes all of the functions that have been bound to that submit event to be executed, and calls the browser's default submit action on the matching element(s). This default action can be prevented by returning false from one of the functions bound to the submit event.Example:
To trigger the submit event on the first form on the page, try:
$("form:first").submit();
-
submit( Function fn ) returns jQuery
Bind a function to the submit event of each matched element.
The select event fires when a form is submittedExample:
If you'd like to prevent forms from being submitted unless a flag variable is set, try:
$("form").submit(function() { if ($("input:first").val() == "correct") { $("span").text("Validated...").show(); return true; } $("span").text("Not valid!").show().fadeOut(1000); return false; });
HTML:
<p>Type 'correct' to validate.</p> <form action="javascript:alert('success!');"> <div> <input type="text" /> <input type="submit" /> </div> </form> <span></span>
Example:
If you'd like to prevent forms from being submitted unless a flag variable is set, try:
$("form").submit( function () { return this.some_flag_variable; } );
-
text( ) returns Array<Element>
Matches all input elements of type text.
Example:
Finds all text inputs.
var input = $(":text").css({background:"yellow", border:"3px red solid"}); $("div").text("For this type jQuery found " + input.length + ".") .css("color", "red"); $("form").submit(function () { return false; }); // so it won't submit
HTML:
<form> <input type="button" value="Input Button"/> <input type="checkbox" /> <input type="file" /> <input type="hidden" /> <input type="image" /> <input type="password" /> <input type="radio" /> <input type="reset" /> <input type="submit" /> <input type="text" /> <select><option>Option<option/></select> <textarea></textarea> <button>Button</button> </form> <div> </div>
-
text( ) returns String
Get the combined 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.Example:
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
var str = $("p:first").text(); $("p:last").html(str);
HTML:
<p><b>Test</b> Paragraph.</p> <p></p>
-
text( ) returns String
Get the combined 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.Example:
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone).
var str = $("p:first").text(); $("p:last").html(str);
HTML:
<p><b>Test</b> Paragraph.</p> <p></p>
-
text( String val ) returns jQuery
Set the text contents of all matched elements.
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).Example:
Add text to the paragraph (notice the bold tag is escaped).
$("p").text("<b>Some</b> new text.");
HTML:
<p>Test Paragraph.</p>
-
text( String val ) returns jQuery
Set the text contents of all matched elements.
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).Example:
Add text to the paragraph (notice the bold tag is escaped).
$("p").text("<b>Some</b> new text.");
HTML:
<p>Test Paragraph.</p>
-
toggle( ) returns jQuery
Toggles each of the set of matched elements.
If they are shown, toggle makes them hidden. If they are hidden, toggle makes them shown.Example:
Toggles all paragraphs.
$("button").click(function () { $("p").toggle(); });
HTML:
<button>Toggle</button> <p>Hello</p> <p style="display: none">Good Bye</p>
-
toggle( Function fn, Function fn ) returns jQuery
Toggle between two function calls every other click.
<p>Whenever a matched element is clicked, the first specified function is fired, when clicked again, the second is fired. All subsequent clicks continue to rotate through the two functions.</p><p>Use unbind("click") to remove.</p>Example:
Click to toggle highlight on the list item.
$("li").toggle( function () { $(this).css("list-style-type", "disc") .css("color", "blue"); }, function () { $(this).css({"list-style-type":"", "color":""}); } );
HTML:
<ul> <li>Go to the store</li> <li>Pick up dinner</li> <li>Debug crash</li> <li>Take a jog</li> </ul>
Example:
To toggle a style on table cells:
$("td").toggle( function () { $(this).addClass("selected"); }, function () { $(this).removeClass("selected"); } );
-
toggleClass( String class ) returns jQuery
Adds the specified class if it is not present, removes the specified class if it is present.
Example:
Toggle the class 'highlight' when a paragraph is clicked.
$("p").click(function () { $(this).toggleClass("highlight"); });
HTML:
<p class="blue">Click to toggle</p> <p class="blue highlight">highlight</p> <p class="blue">on these</p> <p class="blue">paragraphs</p>
-
trigger( String type , Array data ) returns jQuery
Trigger a type of event on every matched element.
<p>This will also cause the default action of the browser with the same name (if one exists) to be executed. For example, passing 'submit' to the trigger() function will also cause the browser to submit the form. This default action can be prevented by returning false from one of the functions bound to the event.</p><p>You can also trigger custom events registered with bind.</p>Example:
Clicks to button #2 also trigger a click for button #1.
$("button:first").click(function () { update($("span:first")); }); $("button:last").click(function () { $("button:first").trigger('click'); update($("span:last")); }); function update(j) { var n = parseInt(j.text(), 0); j.text(n + 1); }
HTML:
<button>Button #1</button> <button>Button #2</button> <div><span>0</span> button #1 clicks.</div> <div><span>0</span> button #2 clicks.</div>
Example:
To submit the first form without using the submit() function, try:
$("form:first").trigger("submit")
Example:
To pass arbitrary data to an event:
$("p").click( function (event, a, b) { // when a normal click fires, a and b are undefined // for a trigger like below a refers too "foo" and b refers to "bar" } ).trigger("click", ["foo", "bar"]);
Example:
This would display a "Hello World!" alert box.
$("p").bind("myEvent", function (event, message1, message2) { alert(message1 + ' ' + message2); }); $("p").trigger("myEvent", ["Hello","World!"]);
-
triggerHandler( String type , Array data ) returns jQuery
This particular method triggers all bound event handlers on an element (for a specific event type) WITHOUT executing the browsers default actions.
Example:
If you called .triggerHandler() on a focus event - the browsers default focus action would not be triggered, only the event handlers bound to the focus event.
$("#old").click(function(){ $("input").trigger("focus"); }); $("#new").click(function(){ $("input").triggerHandler("focus"); }); $("input").focus(function(){ $("<span>Focused!</span>").appendTo("body").fadeOut(1000); });
HTML:
<button id="old">.trigger("focus")</button> <button id="new">.triggerHandler("focus")</button><br/><br/> <input type="text" value="To Be Focused"/>
-
unbind( String type , Function data ) returns jQuery
This does the opposite of bind, it removes bound events from each of the matched elements.
<p>Without any arguments, all bound events are removed.</p><p>You can also unbind custom events registered with bind.</p><p>If the type is provided, all bound events of that type are removed.</p><p>If the function that was passed to bind is provided as the second argument, only that specific event handler is removed.</p>Example:
Can bind and unbind events to the colored button.
function aClick() { $("div").show().fadeOut("slow"); } $("#bind").click(function () { // could use .bind('click', aClick) instead but for variety... $("#theone").click(aClick) .text("Can Click!"); }); $("#unbind").click(function () { $("#theone").unbind('click', aClick) .text("Does nothing..."); });
HTML:
<button id="theone">Does nothing...</button> <button id="bind">Bind Click</button> <button id="unbind">Unbind Click</button> <div style="display:none;">Click!</div>
Example:
To unbind all events from all paragraphs, write:
$("p").unbind()
Example:
To unbind all click events from all paragraphs, write:
$("p").unbind( "click" )
Example:
To unbind just one previously bound handler, pass the function in as the second argument:
var foo = function () { // code to handle some kind of event }; $("p").bind("click", foo); // ... now foo will be called when paragraphs are clicked ... $("p").unbind("click", foo); // ... foo will no longer be called.
-
unload( Function fn ) returns jQuery
Binds a function to the unload event of each matched element.
Example:
To display an alert when a page is unloaded:
$(window).unload( function () { alert("Bye now!"); } );
-
val( ) returns String, Array
Get the content of the value attribute of the first matched element.
In jQuery 1.2, a value is now returned for all elements, including selects. For multiple selects an array of values is returned.
For older versions of jQuery use the [http://www.malsup.com/jquery/form/#fields fieldValue function of the Form Plugin].Example:
Get the single value from a single select and an array of values from a multiple select and display their values.
function displayVals() { var singleValues = $("#single").val(); var multipleValues = $("#multiple").val() || []; $("p").html("<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.join(", ")); } $("select").change(displayVals); displayVals();
HTML:
<p></p> <select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select>
Example:
Find the value of an input box.
$("input").keyup(function () { var value = $(this).val(); $("p").text(value); }).keyup();
HTML:
<input type="text" value="some text"/> <p></p>
-
val( String val ) returns jQuery
Set the value attribute of every matched element.
In jQuery 1.2, this is also able to set the value of select elements, but selecting the appropriate options.Example:
Set the value of an input box.
$("button").click(function () { var text = $(this).text(); $("input").val(text); });
HTML:
<div> <button>Feed</button> <button>the</button> <button>Input</button> </div> <input type="text" value="click a button" />
-
val( Array<String> val ) returns jQuery
Checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
Example:
Get the single value from a single select and an array of values from a multiple select and display their values.
$("#single").val("Single2"); $("#multiple").val(["Multiple2", "Multiple3"]); $("input").val(["check2", "radio1"]);
HTML:
<select id="single"> <option>Single</option> <option>Single2</option> </select> <select id="multiple" multiple="multiple"> <option selected="selected">Multiple</option> <option>Multiple2</option> <option selected="selected">Multiple3</option> </select><br/> <input type="checkbox" value="check1"/> check1 <input type="checkbox" value="check2"/> check2 <input type="radio" name="r" value="radio1"/> radio1 <input type="radio" name="r" value="radio2"/> radio2
-
visible( ) returns Array<Element>
Matches all elements that are visible.
Example:
Make all visible divs turn yellow on click.
$("div:visible").click(function () { $(this).css("background", "yellow"); }); $("button").click(function () { $("div:hidden").show("fast"); });
HTML:
<button>Show hidden to see they don't change</button> <div></div> <div class="starthidden"></div> <div></div> <div></div> <div style="display:none;"></div>
-
width( ) returns Integer
Get the current computed, pixel, width of the first matched element.
In jQuery 1.2, this method is able to find the width of the window and document.Example:
Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body.
function showWidth(ele, w) { $("div").text("The width for the " + ele + " is " + w + "px."); } $("#getp").click(function () { showWidth("paragraph", $("p").width()); }); $("#getd").click(function () { showWidth("document", $(document).width()); }); $("#getw").click(function () { showWidth("window", $(window).width()); });
HTML:
<button id="getp">Get Paragraph Width</button> <button id="getd">Get Document Width</button> <button id="getw">Get Window Width</button> <div> </div> <p> Sample paragraph to test width </p>
-
width( String, Number val ) returns jQuery
Set the CSS width of every matched element.
If no explicit unit was specified (like 'em' or '%') then "px" is concatenated to the value.Example:
To set the width of each div on click to 30px plus a color change.
$("div").one('click', function () { $(this).width(30) .css({cursor:"auto", "background-color":"blue"}); });
HTML:
<div></div> <div></div> <div></div> <div></div> <div></div>
-
wrap( String html ) returns jQuery
Wrap all matched elements with a structure of other elements.
This wrapping process is most useful for injecting additional structure 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 enwrap everything else.
This does not work with elements that contain text. Any necessary text must be added after the wrapping is done.Example:
Wraps a newly created div around all paragraphs.
$("p").wrap("<div class='wrap'></div>");
HTML:
<p>Test Paragraph.</p>
Example:
Wraps a newly created tree of objects around each span.
$("span").wrap("<div><div><p><em><b></b></em></p></div></div>");
HTML:
<span>Span Text</span> <span>Another One</span>
-
wrap( Element elem ) returns jQuery
Wrap all matched elements with a structure of other elements.
Example:
Wraps an element with id of "content" around all paragraphs.
$("p").wrap(document.getElementById('content'));
HTML:
<p>Test Paragraph.</p><div id="content"></div>
Example:
Wraps a jQuery object (in this case a div) around all paragraphs.
$("p").wrap($("<div>"));
HTML:
<p>Test Paragraph.</p> <p>Another Paragraph.</p>
-
wrapAll( String html ) returns jQuery
Wrap all the elements in the matched set into a single wrapper element.
This is different from <a href='Manipulation/wrap'>.wrap()</a> where each element in the matched set would get wrapped with an element.
This wrapping process is most useful for injecting additional structure 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 enwrap everything else.Example:
Wrap a new div around all of the paragraphs.
$("p").wrapAll("<div></div>");
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
Example:
Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.
$("span").wrapAll("<div><div><p><em><b></b></em></p></div></div>");
HTML:
<span>Span Text</span> <strong>What about me?</strong> <span>Another One</span>
-
wrapAll( Element elem ) returns jQuery
Wrap all the elements in the matched set into a single wrapper element.
This is different from <a href='Manipulation/wrap'>.wrap()</a> where each element in the matched set would get wrapped with an element.Example:
Wrap a new div around all of the paragraphs.
$("p").wrapAll(document.createElement("div"));
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
Example:
Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target.
$("p").wrapAll($(".doublediv"));
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p> <div class="doublediv"><div></div></div>
-
wrapInner( String html ) returns jQuery
Wrap the inner child contents of each matched element (including text nodes) with an HTML structure.
This wrapping process is most useful for injecting additional structure 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 enwrap everything else.Example:
Selects all paragraphs and wraps a bold tag around each of its contents.
$("p").wrapInner("<b></b>");
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
Example:
Wraps a newly created tree of objects around the inside of the body.
$("body").wrapInner("<div><div><p><em><b></b></em></p></div></div>");
HTML:
Plain old text, or is it?
-
wrapInner( Element elem ) returns jQuery
Wrap the inner child contents of each matched element (including text nodes) with a DOM element.
Example:
Selects all paragraphs and wraps a bold tag around each of its contents.
$("p").wrapInner(document.createElement("b"));
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>
Example:
Selects all paragraphs and wraps a jQuery object around each of its contents.
$("p").wrapInner($("<span class='red'></span>"));
HTML:
<p>Hello</p> <p>cruel</p> <p>World</p>