1.0This 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 Selectors]]> for the allowed CSS syntax for expressions. An expression to search with.A DOM Element, Document or jQuery to use as contextFinds all p elements that are children of a div element.$("div > p").css("border", "1px solid gray");<p>one</p> <div><p>two</p></div> <p>three</p>[ <p>two</p> ]Finds all inputs of type radio within the first form in the document.$("input:radio", document.forms[0]);Finds all div elements within an XML document from an AJAX response.$("div", xml.responseXML);1.0Create 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.A string of HTML to create on the fly.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")Do not create &lt;input&gt;-Elements without a type-attribute, due to Microsofts read/write-once-rule for the type-attribute of &lt;input&gt;-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'/>");1.0Wrap 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).DOM element(s) to be encapsulated by a jQuery object.Sets the background color of the page to black.$(document.body).css( "background", "black" );Hides all the input elements within a form.$(myForm.elements).hide()1.0A 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. The function to execute when the DOM is ready.Executes the function when the DOM is ready to be used.$(function(){ // Document is ready });Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.jQuery(function($) { // Your code using failsafe $ alias here... });1.0Execute 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). The callback to execute for each matched element. <pre>function callback(index, domElement) { this; // this == domElement } </pre>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 = ""; } }); }); div { color:red; text-align:center; cursor:pointer; font-weight:bolder; width:300px; } <div>Click here</div> <div>to iterate through</div> <div>these divs.</div>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"); }); }); ul { font-size:18px; margin:0; } span { color:blue; text-decoration:underline; cursor:pointer; } .example { font-style:italic; } To do list: <span>(click here to change)</span> <ul> <li>Eat</li> <li>Sleep</li> <li>Be merry</li> </ul>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; } }); }); div { width:40px; height:40px; margin:5px; float:left; border:2px blue solid; text-align:center; } span { color:red; } <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>1.0The number of elements in the jQuery object.This returns the same number as the 'length]]>' property of the jQuery object.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 body { cursor:pointer; } div { width:50px; height:30px; margin:5px; float:left; background:blue; } span { color:red; } <span></span> <div></div>The number of elements in the jQuery object.In a The number of elements currently matched. The size]]> function will return the same value.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 body { cursor:pointer; } div { width:50px; height:30px; margin:5px; float:left; background:green; } span { color:red; } <span></span> <div></div>1.0Reduce 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.The index of the element to select.1.2slice]]>Reduces the selection to the second selected element.$("p").eq(1)<p>This is just a test.</p><p>So is this</p>[ <p>So is this</p> ]1.0Access 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. 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() ); span { color:red; } Reversed - <span></span> <div>One</div> <div>Two</div> <div>Three</div>1.0Access 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].Access the element in the Nth position.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); }); span { color:red; } div { background:yellow; } <span>&nbsp;</span> <p>In this paragraph is an <span>important</span> section</p> <div><input type="text" /></div>1.0Searches 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.Object to search for.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); }); div { background:yellow; margin:5px; } span { color:red; } <span>Click a div!</span> <div>First div</div> <div>Second div</div> <div>Third div</div>Returns the index for the element with ID foobar.$("*").index( $('#foobar')[0] )<div id="foobar"><b></b><span id="foo"></span></div>Returns the index for the element with ID foo within another element.$("*").index( $('#foo')[0] )<div id="foobar"><b></b><span id="foo"></span></div>Returns the index for the element clicked within a collection.var mainNavLinks = $('ul#mainNav li a'); mainNavLinks.click(function(){alert(mainNavLinks.index(this)0;});Returns -1, as there is no element with ID bar.$("*").index( $('#bar')[0] )<div id="foobar"><b></b><span id="foo"></span></div>1.0Extends 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 plugin methods (plugins)]]>. The object that will be merged into the jQuery object.Adds two plugin methods.jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } });$("input[@type=checkbox]").check(); $("input[@type=radio]").uncheck();1.0Extends the jQuery object itself.Can be used to add functions into the jQuery namespace. See jQuery.fn.extend]]> for more information on using this method to add Plugins]]>.The object that will be merged into the jQuery object.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; } });jQuery.min(2,3); // => 2 jQuery.max(4,5); // => 51.0Run 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").Maps the original object that was referenced by $ back to $.jQuery.noConflict(); // Do something with jQuery jQuery("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.jQuery.noConflict(); (function($) { $(function() { // more code using $ as alias to jQuery }); })(jQuery); // other code using $ as an alias to the other libraryCreates 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';1.1.4Revert control of both the $ and jQuery variables to their original owners. '''Use with discretion.'''This is a more-extreme version of the simple noConflict]]> 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.Set to true to enable the extreme rollback of jQuery and it's variables.Completely move jQuery to a new namespace in another object.var dom = {}; dom.query = jQuery.noConflict(true);// 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();#id1.0Matches 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].An ID to search for, specified via the id attribute of an element.Finds the element with the id "myDiv".$("#myDiv").css("border","3px solid red");<div id="notMe"><p>id="notMe"</p></div> <div id="myDiv">id="myDiv"</div> div { width: 90px; height: 90px; float:left; padding: 5px; margin: 5px; background-color: #EEEEEE; } 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");<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> div { width: 300px; float:left; padding: 2px; margin: 3px; background-color: #EEEEEE; } element1.0Matches all elements with the given name. An element to search for. Refers to the tagName of DOM nodes.Finds every DIV element.$("div").css("border","3px solid red");<div>DIV1</div> <div>DIV2</div> <span>SPAN</span> div,span { width: 60px; height: 60px; float:left; padding: 10px; margin: 10px; background-color: #EEEEEE; } .class1.0Matches all elements with the given class. A class to search for. An element can have multiple classes, one of them must match.Finds the element with the class "myClass".$(".myClass").css("border","3px solid red");<div class="notMe">div class="notMe"</div> <div class="myClass">div class="myClass"</div> <span class="myClass">span class="myClass"</span> div,span { width: 150px; height: 60px; float:left; padding: 10px; margin: 10px; background-color: #EEEEEE; } *1.0Matches all elements.Most useful when combined with a context to search in.Finds every element (including head, body, etc).$("*").css("border","3px solid red");<div>DIV</div> <span>SPAN</span> <p>P <button>Button</button></p> div,span,p { width: 150px; height: 60px; float:left; padding: 10px; margin: 10px; background-color: #EEEEEE; } 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");selector1, selector2, selectorN1.0Matches 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.Any valid selectorAnother valid selectorAs many more valid selectors as you likeFinds the elements that match any of these three selectors.$("div,span,p.myClass").css("border","3px solid red");<div>div</div> <p class="myClass">p class="myClass"</p> <p class="notMyClass">p class="notMyClass"</p> <span>span</span> div,span,p { width: 130px; height: 60px; float:left; padding: 3px; margin: 2px; background-color: #EEEEEE; font-size:14px; } Show the order in the jQuery object. var list = $("div,p,span").map(function () { return this.tagName; }).get().join(", "); $("b").append(document.createTextNode(list)); b { color:red; font-size:16px; display:block; clear:left; } div,span,p { width: 40px; height: 40px; float:left; margin: 10px; background-color: blue; padding:3px; color:white; } <span>span</span> <p>p</p> <p>p</p> <div>div</div> <span>span</span> <p>p</p> <div>div</div> <b></b>ancestor descendant1.0Matches all descendant elements specified by "descendant" of elements specified by "ancestor".Any valid selector.A selector to match elements that are descendants of the first selector.Finds all input descendants of forms.$("form input").css("border", "2px dotted blue"); body { font-size:14px; } form { border:2px green solid; padding:2px; margin:0; background:#efe; } div { color:red; } fieldset { margin:1px; padding:3px; } <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" />parent > child1.0Matches all child elements specified by "child" of elements specified by "parent".Any valid selector.A selector to match elements that are children of the first selector.Finds all children of the element with id "main" which is yellow.$("#main > *").css("border", "3px double red"); body { font-size:14px; } span#main { display:block; background:yellow; height:110px; } button { display:block; float:left; margin:2px; font-size:14px; } div { width:90px; height:90px; margin:5px; float:left; background:#bbf; font-weight:bold; } div.mini { width:30px; height:30px; background:green; } <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>prev + next1.0Matches all next elements specified by "next" that are next to elements specified by "prev".Any valid selector.A selector to match elements that are next to the first selector.Finds all inputs that are next to a label.$("label + input").css("color", "blue").val("Labeled!")<form> <label>Name:</label> <input name="name" /> <fieldset> <label>Newsletter:</label> <input name="newsletter" /> </fieldset> </form> <input name="none" />prev ~ siblings1.0Matches all sibling elements after the "prev" element that match the filtering "siblings" selector.Any valid selector.A filter selector to match elements that are following siblings to the first selector.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"); div,span { display:block; width:80px; height:80px; margin:5px; background:#bbffaa; float:left; font-size:14px; } div#small { width:60px; height:25px; font-size:12px; background:#fab; } <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>:first1.0Matches the first selected element.Finds the first table row.$("tr:first").css("font-style", "italic"); td { color:blue; font-weight:bold; } <table> <tr><td>Row 1</td></tr> <tr><td>Row 2</td></tr> <tr><td>Row 3</td></tr> </table>:last1.0Matches the last selected element.Finds the last table row.$("tr:last").css({backgroundColor: 'yellow', fontWeight: 'bolder'});<table> <tr><td>First Row</td></tr> <tr><td>Middle Row</td></tr> <tr><td>Last Row</td></tr> </table>:not(selector)1.1.4Filters out all elements matching the given selector.A selector with which to filter by.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"); <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>:even1.0Matches even elements, zero-indexed.Finds even table rows, matching the first, third and so on (index 0, 2, 4 etc.).$("tr:even").css("background-color", "#bbbbff"); table { background:#eeeeee; } <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>:odd1.0Matches odd elements, zero-indexed.Finds odd table rows, matching the second, fourth and so on (index 1, 3, 5 etc.).$("tr:odd").css("background-color", "#bbbbff"); table { background:#f3f7f5; } <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>:eq(index)1.0Matches a single element by its index.Zero-based index of the element to match.Finds the third td. (annoying blink isn't it)$("td:eq(2)").css("text-decoration", "blink");<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>:gt(index)1.0Matches all elements with an index above the given one.Zero-based index.Finds TD #5 and higher. Reminder: the indexing starts at 0.$("td:gt(4)").css("text-decoration", "line-through");<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>:lt(index)1.0Matches all elements with an index below the given one.Zero-based index.Finds TDs less than the one with the 4th index (TD#4).$("td:lt(4)").css("color", "red");<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>:header1.2Matches all elements that are headers, like h1, h2, h3 and so on.Adds a background and text color to all the headers on the page.$(":header").css({ background:'#CCC', color:'blue' });<h1>Header 1</h1> <p>Contents 1</p> <h2>Header 2</h2> <p>Contents 2</p> body { font-size: 10px; font-family: Arial; } h1, h2 { margin: 3px 0; } :animated1.2Matches all elements that are currently being animated.Change the color of any div that is animated. $("#run").click(function(){ $("div:animated").toggleClass("colored"); }); function animateIt() { $("#mover").slideToggle("slow", animateIt); } animateIt(); <button id="run">Run</button> <div></div> <div id="mover"></div> <div></div> div { background:yellow; border:1px solid #AAA; width:80px; height:80px; margin:5px; float:left; } div.colored { background:green; } :contains(text)1.1.4Matches elements which contain the given text.A string of text to look for. It's case sensitive.Finds all divs containing "John" and underlines them.$("div:contains('John')").css("text-decoration", "underline");<div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn:empty1.0Matches all elements that have no children (including text nodes).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)'); td { text-align:center; } <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>:has(selector)1.1.4Matches elements which contain at least one element that matches the specified selector.A selector with which to filter by.Adds the class "test" to all divs that have a paragraph inside of them.$("div:has(p)").addClass("test");<div><p>Hello in a paragraph</p></div> <div>Hello again! (with no paragraph)</div> .test{ border: 3px inset red; } :parent1.0Matches all elements that are parents - they have child elements, including text.Finds all tds with children, including text.$("td:parent").fadeTo(1500, 0.3); td { width:40px; background:green; } <table border="1"> <tr><td>Value 1</td><td></td></tr> <tr><td>Value 2</td><td></td></tr> </table>:hidden1.0Matches all elements that are hidden, or input elements of type "hidden".Shows all hidden divs and counts hidden inputs. // in some browsers :hidden includes head, title, script, etc... so limit to body $("span:first").text("Found " + $(":hidden", document.body).length + " hidden elements total."); $("div:hidden").show(3000); $("span:last").text("Found " + $("input:hidden").length + " hidden inputs."); div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; } span { display:block; clear:left; color:red; } .starthidden { display:none; } <span></span> <div></div> <div style="display:none;">Hider!</div> <div></div> <div class="starthidden">Hider!</div> <div></div> <form> <input type="hidden" /> <input type="hidden" /> <input type="hidden" /> </form> <span> </span>:visible1.0Matches all elements that are visible.Make all visible divs turn yellow on click. $("div:visible").click(function () { $(this).css("background", "yellow"); }); $("button").click(function () { $("div:hidden").show("fast"); }); div { width:50px; height:40px; margin:5px; border:3px outset green; float:left; } .starthidden { display:none; } <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>[attribute]1.0Matches elements that have the specified attribute.An attribute name.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); }); <div>no id</div> <div id="hey">with id</div> <div id="there">has an id</div> <div>nope</div>[attribute=value]1.0Matches elements that have the specified attribute with a certain value.An attribute name.An attribute value. Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]".Finds all inputs with name 'newsletter' and changes the text of the span next to it.$("input[name='newsletter']").next().text(" is newsletter");<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>[attribute!=value]1.0Matches elements that don't have the specified attribute with a certain value.An attribute name.An attribute value. Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]".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");<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>[attribute^=value]1.0Matches elements that have the specified attribute and it starts with a certain value.An attribute name.An attribute value. Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]".Finds all inputs with an attribute name that starts with 'news' and puts text in them.$("input[name^='news']").val("news here!");<input name="newsletter" /> <input name="milkman" /> <input name="newsboy" />[attribute$=value]1.0Matches elements that have the specified attribute and it ends with a certain value.An attribute name.An attribute value. Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]".Finds all inputs with an attribute name that ends with 'letter' and puts text in them.$("input[name$='letter']").val("a letter");<input name="newsletter" /> <input name="milkman" /> <input name="jobletter" />[attribute*=value]1.0Matches elements that have the specified attribute and it contains a certain value.An attribute name.An attribute value. Quotes are optional in most cases, but should be used to avoid conflicts when the value contains characters like "]".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!");<input name="man-news" /> <input name="milkman" /> <input name="letterman2" /> <input name="newmilk" />[selector1][selector2][selectorN]1.0Matches elements that have the specified attribute and it contains a certain value.An attribute selector.Another attribute selector, reducing the selection even moreAs many more attribute selectors as necessaryFinds 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");<input id="man-news" name="man-news" /> <input name="milkman" /> <input id="letterman" name="new-letterman" /> <input name="newmilk" />:nth-child(index/even/odd/equation)1.1.4Matches the nth-child of its parent or all its even or odd children.While :eq(index)]]> 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.The index of each child to match, starting with 1 or the string even, odd, or equation ( eg. :nth-child(even), :nth-child(4n) )Finds the second li in each matched ul and notes it.$("ul li:nth-child(2)").append("<span> - 2nd!</span>"); div { float:left; } span { color:blue; } <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>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); }); button { display:block; font-size:12px; width:100px; } div { float:left; margin:10px; font-size:10px; border:1px solid black; } span { color:blue; font-size:18px; } #inner { color:red; } td { width:50px; text-align:center; } <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>:first-child1.1.4Matches the first child of its parent.While :first]]> matches only a single element, this matches more then one: One for each parent.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"); }); span { color:#008; } span.sogreen { color:green; font-weight: bolder; } <div> <span>John,</span> <span>Karl,</span> <span>Brandon</span> </div> <div> <span>Glen,</span> <span>Tane,</span> <span>Ralph</span> </div>:last-child1.1.4Matches the last child of its parent.While :last]]> matches only a single element, this matches more then one: One for each parent.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"); }); span.solast { text-decoration:line-through; } <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>:only-child1.1.4Matches the only child of its parent.If the parent has other child elements, nothing is matched.Finds the button with no siblings in each matched div and modifies look.$("div button:only-child").text("Alone").css("border", "2px blue solid"); div { width:100px; height:80px; margin:5px; float:left; background:#b9e } <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>[ <li>Glen</li> ]:input1.0Matches all input, textarea, select and button elements.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 textarea { height:45px; } <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>:text1.0Matches all input elements of type text.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 textarea { height:45px; } <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>:password1.0Matches all input elements of type password.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 textarea { height:45px; } <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>:radio1.0Matches all input elements of type radio.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 textarea { height:45px; } <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>:checkbox1.0Matches all input elements of type checkbox.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 textarea { height:45px; } <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>:submit1.0Matches all input elements of type submit.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 textarea { height:45px; } <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>:image1.0Matches all input elements of type image.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 textarea { height:45px; } <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>:reset1.0Matches all input elements of type reset.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 textarea { height:45px; } <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>:button1.0Matches all input elements of type button.Finds all button inputs. var input = $(":button").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 textarea { height:45px; } <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>:file1.0Matches all input elements of type file.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 textarea { height:45px; } <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>:hidden1.0Matches all elements that are hidden, or input elements of type "hidden".Shows all hidden divs and counts hidden inputs. // in some browsers :hidden includes head, title, script, etc... so limit to body $("span:first").text("Found " + $(":hidden", document.body).length + " hidden elements total."); $("div:hidden").show(3000); $("span:last").text("Found " + $("input:hidden").length + " hidden inputs."); div { width:70px; height:40px; background:#ee77ff; margin:5px; float:left; } span { display:block; clear:left; color:red; } .starthidden { display:none; } <span></span> <div></div> <div style="display:none;">Hider!</div> <div></div> <div class="starthidden">Hider!</div> <div></div> <form> <input type="hidden" /> <input type="hidden" /> <input type="hidden" /> </form> <span> </span>:enabled1.0Matches all elements that are enabled.Finds all input elements that are enabled.$("input:enabled").val("this is it");<form> <input name="email" disabled="disabled" /> <input name="id" /> </form>:disabled1.0Matches all elements that are disabled.Finds all input elements that are disabled.$("input:disabled").val("this is it");<form> <input name="email" disabled="disabled" /> <input name="id" /> </form>:checked1.0Matches all elements that are checked.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); div { color:red; } <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>[ <input type="checkbox" name="newsletter" checked="checked" value="Daily" />, <input type="checkbox" name="newsletter" checked="checked" value="Monthly" /> ]:selected1.0Matches all elements that are selected.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'); div { color:red; } <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>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.The name of the property to access.Finds the title attribute of the first <em> in the page. var title = $("em").attr("title"); $("div").text(title); em { color:blue; font-weight;bold; } div { color:red; } <p> Once there was a <em title="huge, gigantic">large</em> dinosaur... </p> The title of the emphasis is:<div></div>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 ).Key/value pairs to set as object properties.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")); img { padding:10px; } div { color:red; font-size:24px; } <img /> <img /> <img /> <div></div>Set a single property to a value, on all matched elements.The name of the property to set.The value to set the property to.Disables buttons greater than the 0th button.$("button:gt(0)").attr("disabled","disabled"); button { margin:10px; } <button>0th Button</button> <button>1st Button</button> <button>2nd Button</button>Set a single property to a computed value, on all matched elements.Instead of supplying a string value as described above]]>, a function is provided that computes the value.The name of the property to set.A function returning the value to set. Scope: Current element, argument: Index of current element <pre>function callback(indexArray) { // indexArray[0] == position in the jQuery object this; // dom element } </pre>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>')"); }); div { color:blue; } span { color:red; } b { font-weight:bolder; } <div>Zero-th <span></span></div> <div>First <span></span></div> <div>Second <span></span></div>Sets src attribute from title attribute on the image. $("img").attr("src", function() { return "/images/" + this.title; }); <img title="hat.gif"/> <img title="hat-old.gif"/> <img title="hat2-old.gif"/>Remove an attribute from each of the matched elements.The name of the property to remove.Clicking the button enables the input next to it. $("button").click(function () { $(this).next().removeAttr("disabled") .focus() .val("editable now"); }); <button>Enable</button> <input type="text" disabled="disabled" value="can't edit this" />Adds the specified class(es) to each of the set of matched elements.One or more CSS classes to add to the elements, these are separated by spaces.Adds the class 'selected' to the matched elements.$("p:last").addClass("selected"); p { margin: 8px; font-size:16px; } .selected { color:red; } .highlight { background:yellow; } <p>Hello</p> <p>and</p> <p>Goodbye</p>Adds the classes 'selected' and 'highlight' to the matched elements.$("p:last").addClass("selected highlight"); p { margin: 8px; font-size:16px; } .selected { color:red; } .highlight { background:yellow; } <p>Hello</p> <p>and</p> <p>Goodbye</p>Removes all or the specified class(es) from the set of matched elements.One or more CSS classes to remove from the elements, these are separated by spaces.Remove the class 'blue' from the matched elements.$("p:even").removeClass("blue"); p { margin: 4px; font-size:16px; font-weight:bolder; } .blue { color:blue; } .under { text-decoration:underline; } .highlight { background:yellow; } <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>Remove the class 'blue' and 'under' from the matched elements.$("p:odd").removeClass("blue under"); p { margin: 4px; font-size:16px; font-weight:bolder; } .blue { color:blue; } .under { text-decoration:underline; } .highlight { background:yellow; } <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>Remove all the classes from the matched elements.$("p:eq(1)").removeClass(); p { margin: 4px; font-size:16px; font-weight:bolder; } .blue { color:blue; } .under { text-decoration:underline; } .highlight { background:yellow; } <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>Adds the specified class if it is not present, removes the specified class if it is present.A CSS class to toggle on the elements.Toggle the class 'highlight' when a paragraph is clicked. $("p").click(function () { $(this).toggleClass("highlight"); }); p { margin: 4px; font-size:16px; font-weight:bolder; cursor:pointer; } .blue { color:blue; } .highlight { background:yellow; } <p class="blue">Click to toggle</p> <p class="blue highlight">highlight</p> <p class="blue">on these</p> <p class="blue">paragraphs</p>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).Click a paragraph to convert it from html to text. $("p").click(function () { var htmlStr = $(this).html(); $(this).text(htmlStr); }); p { margin:8px; font-size:20px; color:blue; cursor:pointer; } b { text-decoration:underline; } button { cursor:pointer; } <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>Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).Set the html contents to the specified value.Add some html to each div.$("div").html("<span class='red'>Hello <b>Again</b></span>"); .red { color:red; } <span>Hello</span> <div></div> <div></div> <div></div>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"); div { color:blue; font-size:18px; } <div></div> <div></div> <div></div>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.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); p { color:blue; margin:8px; } b { color:red; } <p><b>Test</b> Paragraph.</p> <p></p>Set the text contents of all matched elements.Similar to html(), but escapes HTML (replace "<" and ">" with their HTML entities).The text value to set the contents of the element to.Add text to the paragraph (notice the bold tag is escaped).$("p").text("<b>Some</b> new text."); p { color:blue; margin:8px; } <p>Test Paragraph.</p>1.0Get 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].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(); p { color:red; margin:4px; } b { color:blue; } <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>Find the value of an input box. $("input").keyup(function () { var value = $(this).val(); $("p").text(value); }).keyup(); p { color:blue; margin:8px; } <input type="text" value="some text"/> <p></p>1.0Set 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.The value to set on the matched element.Set the value of an input box. $("button").click(function () { var text = $(this).text(); $("input").val(text); }); button { margin:4px; cursor:pointer; } input { margin:4px; color:blue; } <div> <button>Feed</button> <button>the</button> <button>Input</button> </div> <input type="text" value="click a button" />1.2Checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.The set of values to check/select.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"]); body { color:blue; } <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"/> radio21.1.2Reduce 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.The index of the element in the jQuery object.Turn the div with index 2 red by adding an appropriate class. $("div").eq(2).addClass("red"); div { width:60px; height:60px; margin:10px; float:left; border:2px solid blue; } .red { background:red; } <div></div> <div></div> <div></div> <div></div> <div></div> <div></div>1.2Checks 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).The class to match.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); }); div { width: 80px; height: 80px; background: #abc; position: relative; border: 2px solid black; margin: 20px 0px; float: left; left:0 } div.protected { border-color: red; } span { display:block; float:left; width:20px; height:20px; } <span></span><div class="protected"></div> <span></span><div></div> <span></span><div></div> <span></span><div class="protected"></div>1.0Removes 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.An expression to pass into the filterChange the color of all divs then put a border around only some of them. $("div").css("background", "#c8ebcc") .filter(".middle") .css("border-color", "red"); div { width:60px; height:60px; margin:5px; float:left; border:2px white solid;} <div></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div></div>Selects all paragraphs and removes those without a class "selected".$("p").filter(".selected")Selects all paragraphs and removes those that aren't of class "selected" or the first one.$("p").filter(".selected, :first")1.0Removes 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 $.each]]>). If the function returns false, then the element is removed - anything else and the element is kept.A function to pass into the filter <pre>function callback(indexInJQueryObject) { var keepItBoolean = true; this; // dom element return keepItBoolean; } </pre>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"); div { width:60px; height:60px; margin:5px; float:left; border:3px white solid; } <div id="first"></div> <div id="second"></div> <div id="third"></div> <div id="fourth"></div> <div id="fifth"></div> <div id="sixth"></div>Remove all elements that have a descendant ol element $("p").filter(function(index) { return $("ol", this).length == 0; });1.0Checks 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'. filter]]> is used internally, therefore all rules that apply there apply here, as well. The expression with which to filterShows 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"}); }); div { width:60px; height:60px; margin:5px; float:left; border:4px outset; background:green; text-align:center; font-weight:bolder; cursor:pointer; } .blue { background:blue; } .red { background:red; } span { color:white; font-size:16px; } p { color:red; font-weight:bolder; background:yellow; margin:3px; clear:left; display:none; } <div></div> <div class="blue"></div> <div></div> <div class="red"></div> <div><br/><span>Peter</span></div> <div class="blue"></div> <p>&nbsp;</p>Returns true, because the parent of the input is a form element var isFormParent = $("input[@type='checkbox']").parent().is("form") $("div").text("isFormParent = " + isFormParent); div { color:red; }<form><input type="checkbox" /></form> <div></div>Returns false, because the parent of the input is a p element var isFormParent = $("input[@type='checkbox']").parent().is("form") $("div").text("isFormParent = " + isFormParent); div { color:red; }<form><p><input type="checkbox" /></p></form> <div></div>1.2Translate 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 $.map()]]>.The function to execute on each element in the set. <pre>function callback(index, domElement) { var replacement; this; // also dom element // replacement == null : delete spot // replacement == array : insert the elements of the array // else replace the spot with replacement return replacement; } </pre>Build a list of all the values within a form. $("p").append( $("input").map(function(){ return $(this).val(); }).get().join(", ") ); p { color:red; } <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>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); body { font-size:16px; } ul { float:left; margin:0 30px; color:blue; } #results { color:red; } <ul> <li>First</li> <li>Second</li> <li>Third</li> <li>Fourth</li> <li>Fifth</li> </ul> <ul id="results"> </ul>1.0Removes elements matching the specified expression from the set of matched elements.An expression with which to remove matching elements, an element to remove from the set or a set of elements to remove from the jQuery set of matched elements.Adds a border to divs that are not green or blue. $("div").not(".green, #blueone") .css("border-color", "red"); div { width:60px; height:60px; margin:10px; float:left; background:yellow; border:2px solid white; } .green { background:#8f8; } .gray { background:#ccc; } #blueone { background:#99f; } <div></div> <div id="blueone"></div> <div></div> <div class="green"></div> <div class="green"></div> <div class="gray"></div> <div></div>Removes the element with the ID "selected" from the set of all paragraphs.$("p").not( $("#selected")[0] )Removes the element with the ID "selected" from the set of all paragraphs.$("p").not("#selected")Removes all elements that match "div p.selected" from the total set of all paragraphs.$("p").not($("div p.selected"))1.1.4Selects a subset of the matched elements.Behaves exactly like the built-in Array slice method. Where to start the subset. The first element is at zero. Can be negative to start from the end of the selection.Where to end the subset. If unspecified, ends at the end of the selection.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); div { width:40px; height:40px; margin:10px; float:left; border:2px solid blue; } span { color:red; font-weight:bold; } button { margin:5px; } <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>Selects all paragraphs, then slices the selection to include only the first element.$("p").slice(0, 1).wrapInner("<b></b>");Selects all paragraphs, then slices the selection to include only the first and second element.$("p").slice(0, 2).wrapInner("<b></b>");Selects all paragraphs, then slices the selection to include only the second element.$("p").slice(1, 2).wrapInner("<b></b>");Selects all paragraphs, then slices the selection to include only the second and third element.$("p").slice(1).wrapInner("<b></b>");Selects all paragraphs, then slices the selection to include only the third element.$("p").slice(-1).wrapInner("<b></b>");1.0Adds more elements, matched by the given expression, to the set of matched elements.An expression whose matched elements are added for String, a string of HTML to create on the fly for DOMElement or one or more Elements to add if an Array.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"); div { width:60px; height:60px; margin:10px; float:left; } p { clear:left; font-weight:bold; font-size:16px; color:blue; margin:0 10px; padding:2px; } <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <p>Added this... (notice no border)</p>Adds more elements, matched by the given expression, to the set of matched elements.$("p").add("span").css("background", "yellow");<p>Hello</p><span>Hello Again</span>Adds more elements, created on the fly, to the set of matched elements.$("p").clone().add("&lt;span>Again&lt;/span>").appendTo(document.body);<p>Hello</p>Adds one or more Elements to the set of matched elements.$("p").add(document.getElementById("a")).css("background", "yellow");<p>Hello</p><span id="a">Hello Again</span>1.0Get 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.An expression to filter the child Elements with.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; }); body { font-size:16px; font-weight:bolder; } div { width:130px; height:82px; margin:10px; float:left; border:1px solid blue; padding:4px; } #container { width:auto; height:105px; margin:0; float:none; border:none; } .hilite { border-color:red; } #results { display:block; color:red; } p { margin:10px; border:1px solid transparent; } span { color:blue; border:1px solid transparent; } input { width:100px; } em { border:1px solid transparent; } a { border:1px solid transparent; } b { border:1px solid transparent; } button { border:1px solid transparent; } <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>Find all children of each div.$("div").children().css("border-bottom", "3px double red"); body { font-size:16px; font-weight:bolder; } span { color:blue; } p { margin:5px 0; } <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>Find all children with a class "selected" of each div.$("div").children(".selected").css("color", "blue"); body { font-size:16px; font-weight:bolder; } p { margin:5px 0; } <div> <span>Hello</span> <p class="selected">Hello Again</p> <div class="selected">And Again</div> <p>And One Last Time</p> </div>1.2Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.Find all the text nodes inside a paragraph and wrap them with a bold tag.$("p").contents().not("[nodeType=1]").wrap("<b/>");<p>Hello <a href="http://ejohn.org/">John</a>, how are you doing?</p>Append some new content into an empty iframe.$("iframe").contents().find("body").append("I'm in an iframe!");<iframe src="/index-blank.html" width="300" height="100"></iframe>1.0Searches for all elements that match the specified expression]]>. This method is a good way to find additional descendant elements with which to process.All searching is done using a jQuery expression]]>. The expression can be written using CSS 1-3 Selector syntax. An expression to search with.Starts with all paragraphs and searches for descendant span elements, same as $("p span")$("p").find("span").css('color','red');<p><span>Hello</span>, how are you?</p> <p>Me? I'm <span>good</span>.</p>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"}); p { font-size:20px; width:200px; cursor:default; color:blue; font-weight:bold; margin:0 10px; } .hilite { background:yellow; } <p> When the day is short find that which matters to you or stop believing </p>1.0Get 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. An expression with which to filter the returned set.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"); span { color:blue; font-weight:bold; } button { width:100px; } <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>Find the very next sibling of each paragraph that has a class "selected".$("p").next(".selected").css("background", "yellow");<p>Hello</p> <p class="selected">Hello Again</p> <div><span>And Again</span></div>1.2Find all sibling elements after the current element.Use an optional expression to filter the matched set. An expression to filter the next Elements with.Locate all the divs after the first and give them a class.$("div:first").nextAll().addClass("after"); div { width: 80px; height: 80px; background: #abc; border: 2px solid black; margin: 10px; float: left; } div.after { border-color: red; } <div></div> <div></div> <div></div> <div></div>Locate all the paragraphs after the second child in the body and give them a class. $(":nth-child(1)").nextAll("p").addClass("after"); div, p { width: 60px; height: 60px; background: #abc; border: 2px solid black; margin: 10px; float: left; } .after { border-color: red; } <p>p</p> <div>div</div> <p>p</p> <p>p</p> <div>div</div> <p>p</p> <div>div</div>1.0Get 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. An expression to filter the parents with.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 + " > ")); }); div,p { margin:10px; } <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>Find the parent element of each paragraph with a class "selected".$("p").parent(".selected").css("background", "yellow");<div><p>Hello</p></div> <div class="selected"><p>Hello Again</p></div> 1.0Get 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. An expression to filter the ancestors withFind all parent elements of each span. var parentEls = $("b").parents() .map(function () { return this.tagName; }) .get().join(", "); $("b").append("<strong>" + parentEls + "</strong>"); b { color:blue; } strong { color:red; } <div> <p> <span> <b>My parents are: </b> </span> </p> </div>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(); }); p, div, span {margin:2px; padding:1px; } div { border:2px white solid; } span { cursor:pointer; font-size:12px; } .selected { color:blue; } b { color:red; display:block; font-size:14px; } <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>1.0Get 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. An expression to filter the previous Elements with.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"); }); div { width:40px; height:40px; margin:10px; float:left; border:2px blue solid; padding:2px; } span { font-size:14px; } p { clear:left; margin:10px; } <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>Find the very previous sibling of each paragraph that has a class "selected".$("p").prev(".selected").css("background", "yellow");<div><span>Hello</span></div> <p class="selected">Hello Again</p> <p>And Again</p>1.2Find all sibling elements before the current element.Use an optional expression to filter the matched set. An expression to filter the previous Elements with.Locate all the divs before the last and give them a class.$("div:last").prevAll().addClass("before"); div { width:70px; height:70px; background:#abc; border:2px solid black; margin:10px; float:left; } div.before { border-color: red; } <div></div> <div></div> <div></div> <div></div>1.0Get 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. An expression to filter the sibling Elements withFind the unique siblings of all yellow li elements in the 3 lists (including other yellow li element