cdnbitbucketorg httpcdnbitbucketorggreydwarfjquerydocdownloadsjquery_refhtml
JQuery Documentation
Core
jQueryholdReady
Holds or releases the execut ion of jQuerys ready event
Added in version 16
jQueryholdReady(hold)undef ined
holdBoolean Indicates whether the ready hold is being requested or released
The $holdReady() method allows the caller to delay jQuerys ready event This advancedfeature would typically be used by dynamic script loaders that want to load addit ionalJavaScript such as jQuery plugins before allowing the ready event to occur even though theDOM may be ready This method must be called early in the document such as in the ltheadgtimmediately af ter the jQuery script tag Calling this method af ter the ready event has alreadyf ired will have no ef fect
To delay the ready event f irst call $holdReady(true) When the ready event should be releasedto execute call $holdReady(false) Note that mult iple holds can be put on the ready event onefor each $holdReady(true) call The ready event will not actually f ire unt il all holds have beenreleased with a corresponding $holdReady(false) and the normal document ready condit ionsare met (See ready for more informat ion)
Example 1 Delay the ready event unt il a custom plugin has loaded
Javascript
$holdReady(true)$getScript(mypluginjs function() $holdReady(false))
jQuerywhen
Provides a way to execute callback funct ions based on one or more objects usually Deferredobjects that represent asynchronous events
Added in version 15
jQuerywhen(deferreds)Promise
deferredsDeferred One or more Deferred objects or plain JavaScript objects
If a single Deferred is passed to jQuerywhen its Promise object (a subset of the Deferredmethods) is returned by the method Addit ional methods of the Promise object can be called toattach callbacks such as deferredthen When the Deferred is resolved or rejected usually bythe code that created the Deferred originally the appropriate callbacks will be called Forexample the jqXHR object returned by jQueryajax is a Deferred and can be used this way
$when( $ajax(testaspx) )then(function(ajaxArgs) alert(ajaxArgs[1]) ajaxArgs is [ success statusText jqXHR ] )
If a single argument is passed to jQuerywhen and it is not a Deferred it will be t reated as aresolved Deferred and any doneCallbacks at tached will be executed immediately ThedoneCallbacks are passed the original argument In this case any failCallbacks you might set arenever called since the Deferred is never rejected For example
$when( testing 123 )done( function(x) alert(xtesting) alerts 123 )
In the case where mult iple Deferred objects are passed to jQuerywhen the method returns thePromise from a new master Deferred object that t racks the aggregate state of all theDeferreds it has been passed The method will resolve its master Deferred as soon as all theDeferreds resolve or reject the master Deferred as soon as one of the Deferreds is rejected Ifthe master Deferred is resolved it is passed the resolved values of all the Deferreds that werepassed to jQuerywhen For example when the Deferreds are jQueryajax() requests thearguments will be the jqXHR objects for the requests in the order they were given in theargument list
In the mult iple-Deferreds case where one of the Deferreds is rejected jQuerywhen immediatelyf ires the failCallbacks for its master Deferred Note that some of the Deferreds may st ill beunresolved at that point If you need to perform addit ional processing for this case such ascanceling any unf inished ajax requests you can keep references to the underlying jqXHRobjects in a closure and inspectcancel them in the failCallback
Example 1 Execute a funct ion af ter two ajax requests are successful (See the jQueryajax()documentat ion for a complete descript ion of success and error cases for an ajax request)
Javascript
$when($ajax(page1php) $ajax(page2php))done(function(a1 a2) a1 and a2 are arguments resolved for the page1 and page2 ajax requests respectively var jqXHR = a1[2] arguments are [ success statusText jqXHR ] i f ( Whip Ittest(jqXHRresponseText) ) alert(First page has Whip It somewhere) )
Example 2 Execute the funct ion myFunc when both ajax requests are successful or myFailureif either one has an error
Javascript
$when($ajax(page1php) $ajax(page2php)) then(myFunc myFailure)
jQuerysub
Creates a new copy of jQuery whose propert ies and methods can be modif ied withoutaf fect ing the original jQuery object
Added in version 15
jQuerysub()jQuery
There are two specif ic use cases for which jQuerysub() was created The f irst was for providinga painless way of overriding jQuery methods without completely destroying the originalmethods and another was for helping to do encapsulat ion and basic namespacing for jQueryplugins
Note that jQuerysub() doesnt at tempt to do any sort of isolat ion - that s not its intent ion Allthe methods on the subd version of jQuery will st ill point to the original jQuery (events boundand triggered will st ill be through the main jQuery data will be bound to elements through themain jQuery Ajax queries and events will run through the main jQuery etc)
Note that if youre looking to use this for plugin development you should f irst strongly considerusing something like the jQuery UI widget factory which manages both state and plugin sub-methods Some examples of using the jQuery UI widget factory to build a plugin
The part icular use cases of this method can be best described through some examples
Example 1 Adding a method to a jQuery sub so that it isnt exposed externally
Javascript
(function() var sub$ = jQuerysub()
sub$fnmyCustomMethod = function() return just for me
sub$(document)ready(function() sub$(body)myCustomMethod() just for me ) )() typeof jQuery(body)myCustomMethod undefined
Example 2 Override some jQuery methods to provide new funct ionality
Javascript
(function() var myjQuery = jQuerysub()
myjQueryfnremove = function() New functionality Trigger a remove event thistrigger(remove)
Be sure to call the original jQuery remove method return jQueryfnremoveapply( this arguments )
myjQuery(function($) $(menu)cl ick(function() $(this)find(submenu)remove() )
A new remove event is now triggered from this copy of jQuery $(document)bind(remove function(e) $(etarget)parent()hide() ) ))()
Regular jQuery doesnt trigger a remove event when removing an element This functionality is only contained within the modified myjQuery
Example 3 Create a plugin that returns plugin-specif ic methods
Javascript
(function() Create a new copy of jQuery using sub() var plugin = jQuerysub()
Extend that copy with the new plugin methods pluginfnextend( open function() return thisshow() close function() return thishide() )
Add our plugin to the original jQuery jQueryfnmyplugin = function() thisaddClass(plugin)
Make sure our plugin returns our special plugin version of jQuery return plugin( this ) )()
$(document)ready(function() Call the plugin open method now exists $(main)myplugin()open()
Note Call ing just $(main)open() wont work as open doesnt exist)
jQuerynoConflict
Relinquish jQuerys control of the $ variable
Added in version 10
jQuerynoConf lict (removeAll)Object
removeAllBoolean (opt ional) A Boolean indicat ing whether to remove all jQueryvariables f rom the global scope (including jQuery itself )
Many JavaScript libraries use $ as a funct ion or variable name just as jQuery does In jQueryscase $ is just an alias for jQuery so all funct ionality is available without using $ If we need touse another JavaScript library alongside jQuery we can return control of $ back to the otherlibrary with a call to $noConf lict ()
ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() Code that uses other l ibrarys $ can follow hereltscriptgt
This technique is especially ef fect ive in conjunct ion with the ready() methods ability to aliasthe jQuery object as within callback passed to ready() we can use $ if we wish without fear ofconf licts later
ltscript type=textjavascript src=other_libjsgtltscriptgtltscript type=textjavascript src=jqueryjsgtltscriptgtltscript type=textjavascriptgt $noConfl ict() jQuery(document)ready(function($) Code that uses jQuerys $ can follow here ) Code that uses other l ibrarys $ can follow hereltscriptgt
If necessary we can free up the jQuery name as well by passing true as an argument to themethod This is rarely necessary and if we must do this (for example if we need to use mult ipleversions of the jQuery library on the same page) we need to consider that most plug-ins relyon the presence of the jQuery variable and may not operate correct ly in this situat ion
Example 1 Maps the original object that was referenced by $ back to $
Javascript
jQuerynoConfl ict() Do something with jQueryjQuery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none
Example 2 Reverts the $ alias and then creates and executes a funct ion to provide the $ as ajQuery alias inside the funct ions scope Inside the funct ion the original $ object is not availableThis works well for most plugins that dont rely on any other library
Javascript
jQuerynoConfl ict()(function($) $(function() more code using $ as alias to jQuery ))(jQuery) other code using $ as an alias to the other l ibrary
Example 3 You can chain the jQuerynoConf lict () with the shorthand ready for a compact code
Javascript
jQuerynoConfl ict()(function() code using jQuery) other code using $ as an alias to the other l ibrary
Example 4 Creates a dif ferent alias instead of jQuery to use in the rest of the script
Javascript
var j = jQuerynoConfl ict() Do something with jQueryj(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none
Example 5 Completely move jQuery to a new namespace in another object
Javascript
var dom = domquery = jQuerynoConfl ict(true)
Results
Do something with the new jQuerydomquery(div p)hide() Do something with another l ibrarys $()$(content)styledisplay = none Do something with another version of jQueryjQuery(div gt p)hide()
jQuery
Accepts a string containing a CSS selector which is then used to match a set of elements
Added in version 14
jQuery()jQuery
In the f irst formulat ion listed above jQuery() acirceurordquo which can also be writ ten as $() acirceurordquo searchesthrough the DOM for any elements that match the provided selector and creates a new jQueryobject that references these elements
$(divfoo)
Selector Context
By default selectors perform their searches within the DOM start ing at the document rootHowever an alternate context can be given for the search by using the opt ional secondparameter to the $() funct ion For example to do a search within an event handler the searchcan be restricted like so
$(divfoo)cl ick(function() $(span this)addClass(bar))
When the search for the span selector is restricted to the context of this only spans within theclicked element will get the addit ional class
Internally selector context is implemented with the f ind() method so $(span this) is equivalentto $(this)f ind(span)
Using DOM elements
The second and third formulat ions of this funct ion create a jQuery object using one or moreDOM elements that were already selected in some other way A common use of this facility isto call jQuery methods on an element that has been passed to a callback funct ion through thekeyword this
$(divfoo)cl ick(function() $(this)sl ideUp())
This example causes elements to be hidden with a sliding animat ion when clicked Because thehandler receives the clicked item in the this keyword as a bare DOM element the element mustbe passed to the $() funct ion before applying jQuery methods to it
XML data returned from an Ajax call can be passed to the $() funct ion so individual elements of
the XML structure can be retrieved using f ind() and other DOM traversal methods
$post(urlxml function(data) var $child = $(data)find(child))
Cloning jQuery Objects
When a jQuery object is passed to the $() funct ion a clone of the object is created This newjQuery object references the same DOM elements as the init ial one
Returning an Empty Set
As of jQuery 14 calling the jQuery() method with no arguments returns an empty jQuery set(with a length property of 0) In previous versions of jQuery this would return a set containingthe document node
Example 1 Find all p elements that are children of a div element and apply a border to them
Javascript
$(div gt p)css(border 1px solid gray)
HTML
ltpgtoneltpgt ltdivgtltpgttwoltpgtltdivgt ltpgtthreeltpgt
Example 2 Find all inputs of type radio within the f irst form in the document
Javascript
$(inputradio documentforms[0])
Example 3 Find all div elements within an XML document f rom an Ajax response
Javascript
$(div xmlresponseXML)
Example 4 Set the background color of the page to black
Javascript
$(documentbody)css( background black )
Example 5 Hide all the input elements within a form
Javascript
$(myFormelements)hide()
jQuery
Creates DOM elements on the f ly f rom the provided string of raw HTML
Added in version 14
jQuery(html props)jQuery
htmlString A string def ining a single standalone HTML element (eg ltdivgt orltdivgtltdivgt)
propsObject An map of at t ributes events and methods to call on the newly-createdelement
Creating New Elements
If a string is passed as the parameter to $() jQuery examines the string to see if it looks likeHTML (ie it has lttag gt somewhere within the string) If not the string is interpreted as aselector expression as explained above But if the string appears to be an HTML snippetjQuery at tempts to create new DOM elements as described by the HTML Then a jQuery objectis created and returned that refers to these elements You can perform any of the usual jQuerymethods on this object
$(ltp id=testgtMy ltemgtnewltemgt textltpgt)appendTo(body)
If the HTML is more complex than a single tag without at t ributes as it is in the above examplethe actual creat ion of the elements is handled by the browsers innerHTML mechanism In mostcases jQuery creates a new
element and sets the innerHTML property of the element to the HTML snippet that was passedin When the parameter has a single tag such as$(ltimgAcirc gt) or $(ltagtltagt) jQuery creates the element using the nat ive JavaScriptcreateElement() funct ion
When passing in complex HTML some browsers may not generate a DOM that exact ly
replicates the HTML source provided As ment ioned we use the browsers innerHTML propertyto parse the passed HTML and insert it into the current document During this process somebrowsers f ilter out certain elements such as lthtmlgt ltt it legt or ltheadgt elements As a result the elements inserted may not be representat ive of the original string passed
Filtering isnt however just limited to these tags For example Internet Explorer prior to version 8will also convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer
To ensure cross-plat form compat ibility the snippet must be well-formed Tags that can containother elements should be paired with a closing tag
$(lta href=httpjquerycomgtltagt)
Alternat ively jQuery allows XML-like tag syntax (with or without a space before the slash)
$(ltagt)
Tags that cannot contain elements may be quick-closed or not
$(ltimg gt)$(ltinputgt)
When passing HTML to jQuery() please also note that text nodes are not t reated as DOMelements With the except ion of a few methods (such as content()) they are generallyotherwise ignored or removed Eg
var el = $(1ltbrgt2ltbrgt3) returns [ltbrgt 2 ltbrgt] el = $(1ltbrgt2ltbrgt3 gt) returns [ltbrgt 2 ltbrgt 3 ampgt]
This behaviour is expected
As of jQuery 14 the second argument to jQuery() can accept a map consist ing of a supersetof the propert ies that can be passed to the at t r() method Furthermore any event type can bepassed in and the following jQuery methods can be called val css html text data widthheight or of fset The name class must be quoted in the map since it is a JavaScript reservedword and className cannot be used since it is not the correct at t ribute name
Note Internet Explorer will not allow you to create an input or button element and change itstype you must specify the type using ltinput type=checkbox gt for example A demonstrat ionof this can be seen below
Unsupported in IE
$(ltinput gt type text name test)appendTo(body)
Supported workaround
$(ltinput type=text gt)attr( name test)appendTo(body)
Example 1 Create a div element (and all of its contents) dynamically and append it to the bodyelement Internally an element is created and its innerHTML property set to the given markup
Javascript
$(ltdivgtltpgtHelloltpgtltdivgt)appendTo(body)
Example 2 Create some DOM elements
Javascript
$(ltdivgt class test text Click me cl ick function() $(this)toggleClass(test) )appendTo(body)
jQuery
Binds a funct ion to be executed when the DOM has f inished loading
Added in version 10
jQuery(callback)jQuery
callbackFunct ion The funct ion to execute when the DOM is ready
This funct ion behaves just like $(document)ready() in that it should be used to wrap other $()operat ions on your page that depend on the DOM being ready While this funct ion is
technically chainable there really isnt much use for chaining against it
Example 1 Execute the funct ion when the DOM is ready to be used
Javascript
$(function() Document is ready )
Example 2 Use both the shortcut for $(document)ready() and the argument to write failsafejQuery code using the $ alias without relying on the global alias
Javascript
jQuery(function($) Your code using failsafe $ alias here )
Selectors
focus $(focus)
Selects element if it is current ly focused
Added in version 16
$(focus)
As with other pseudo-class selectors (those that begin with a ) it is recommended toprecede focus with a tag name or some other selector otherwise the universal selector () isimplied In other words the bare $(focus) is equivalent to $(focus) If you are looking for thecurrent ly focused element $( documentact iveElement ) will retrieve it without having to searchthe whole DOM tree
Example 1 Adds the focused class to whatever element has focus
Javascript
$()l ive(focus blur function(e) var el = $(this) setTimeout(function() eltoggleClass(focused elis(focus)) 0))
CSS
focused background abcdef
HTML
ltinput tabIndex=1gtltinput tabIndex=2gtltselect tabIndex=3gt ltoptiongtselect menultoptiongtltselectgtltdiv tabIndex=4gt a divltdivgt
selected $(selected)
Selects all elements that are selected
Added in version 10
$(selected)
The selected selector works for ltopt iongt elements It does not work for checkboxes or radioinputs use checked for them
Example 1 Attaches a change event to the select that gets the text for each selected opt ionand writes them in the div It then triggers the event for the init ial text draw
Javascript
$(select)change(function () var str = $(select optionselected)each(function () str += $(this)text() + ) $(div)text(str) ) trigger(change)
CSS
div colorred
HTML
ltselect name=garden multiple=multiplegt
ltoptiongtFlowersltoptiongt ltoption selected=selectedgtShrubsltoptiongt ltoptiongtTreesltoptiongt ltoption selected=selectedgtBushesltoptiongt
ltoptiongtGrassltoptiongt ltoptiongtDirtltoptiongt ltselectgt ltdivgtltdivgt
checked $(checked)
Matches all elements that are checked
Added in version 10
$(checked)
The checked selector works for checkboxes and radio buttons For select elements use theselected selector
Example 1 Finds all input elements that are checked
Javascript
function countChecked() var n = $(inputchecked)length $(div)text(n + (n lt= 1 is are) + checked)countChecked()$(checkbox)cl ick(countChecked)
CSS
div colorred
HTML
ltformgt ltpgt ltinput type=checkbox name=newsletter checked=checked value=Hourly gt
ltinput type=checkbox name=newsletter value=Daily gt ltinput type=checkbox name=newsletter value=Weekly gt
ltinput type=checkbox name=newsletter checked=checked value=Monthly gt ltinput type=checkbox name=newsletter value=Yearly gt ltpgtltformgtltdivgtltdivgt
Example 2
Javascript
$(input)cl ick(function() $(log)html( $(checked)val() + is checked ))
CSS
input label l ine-height 15em
HTML
ltformgt ltdivgt ltinput type=radio name=fruit value=orange id=orangegt ltlabel for=orangegtorangeltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=apple id=applegt ltlabel for=applegtappleltlabelgt ltdivgt ltdivgt ltinput type=radio name=fruit value=banana id=bananagt ltlabel for=bananagtbananaltlabelgt ltdivgt ltdiv id=loggtltdivgtltformgt
disabled $(disabled)
Selects all elements that are disabled
Added in version 10
$(disabled)
As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(disabled) is equivalent to $(disabled) so $(inputdisabled) should beused instead
Example 1 Finds all input elements that are disabled
Javascript
$(inputdisabled)val(this is it)
HTML
ltformgt
ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt
enabled $(enabled)
Selects all elements that are enabled
Added in version 10
$(enabled)
As with other pseudo-class selectors (those that begin with a ) it is recommended to precedeit with a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(enabled) is equivalent to $(enabled) so $(inputenabled) should beused instead
Example 1 Finds all input elements that are enabled
Javascript
$(inputenabled)val(this is it)
HTML
ltformgt
ltinput name=email disabled=disabled gt ltinput name=id gt ltformgt
file $(file)
Selects all elements of type f ile
Added in version 10
$(f ile)
f ile is equivalent to [type=f ile] As with other pseudo-class selectors (those that begin with a) it is recommended to precede it with a tag name or some other selector otherwise theuniversal selector () is implied In other words the bare $(f ile) is equivalent to $(f ile) so$(inputf ile) should be used instead
Example 1 Finds all f ile inputs
Javascript
var input = $(inputfi le)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height45px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt
button $(button)
Selects all but ton elements and elements of type button
Added in version 10
$(button)
Example 1 Finds all but ton inputs
Javascript
var input = $(button)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height45px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt
reset $(reset)
Selects all elements of type reset
Added in version 10
$(reset)
reset is equivalent to [type=reset]
Example 1 Finds all reset inputs
Javascript
var input = $(inputreset)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height45px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt
image $(image)
Selects all elements of type image
Added in version 10
$(image)
image is equivalent to [type=image]
Example 1 Finds all image inputs
Javascript
var input = $(inputimage)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height45px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt
submit $(submit)
Selects all elements of type submit
Added in version 10
$(submit)
The submit selector typically applies to button or input elements Note that some browserstreat ltbuttongt element as type=default implicit ly while others (such as Internet Explorer) donot
Example 1 Finds all submit elements that are descendants of a td element
Javascript
var submitEl = $(td submit) parent(td) css(backgroundyellow border3px red solid) end() $(result)text( jQuery matched + submitEllength + elements)
so it wont submit $(form)submit(function () return false ) Extra JS to make the HTML easier to edit (None of this is relevant to the submit selector $(exampleTable)find(td)each(function(i el) var inputEl = $(el)children() inputType = inputElattr(type) type= + inputElattr(type) + $(el)before(lttdgt + inputEl[0]nodeName + inputType + lttdgt) )
CSS
textarea height45px
HTML
lttablegtltformgtlttable id=exampleTable border=1 cellpadding=10 align=centergt
lttrgt ltthgt Element Type ltthgt ltthgt Element ltthgt
lttr lttrgt lttdgt ltinput type=button value=Input Buttongt lttdgt
lttrgt lttrgt lttdgt ltinput type=checkbox gt lttdgt
lttrgt lttrgt lttdgt ltinput type=fi le gt lttdgt
lttrgt lttrgt lttdgt ltinput type=hidden gt lttdgt
lttrgt lttrgt lttdgt ltinput type=image gt lttdgt
lttrgt lttrgt lttdgt ltinput type=password gt lttdgt
lttrgt lttrgt lttdgt ltinput type=radio gt lttdgt
lttrgt lttrgt lttdgt ltinput type=reset gt lttdgt
lttrgt lttrgt lttdgt ltinput type=submit gt lttdgt
lttrgt lttrgt lttdgt ltinput type=text gt lttdgt
lttrgt lttrgt lttdgt ltselectgtltoptiongtOptionltoptiongtltselectgt lttdgt
lttrgt lttrgt lttdgt lttextareagtlttextareagt lttdgt lttrgt
lttrgt lttdgt ltbuttongtButtonltbuttongt lttdgt lttrgt lttrgt lttdgt ltbutton type=submitgtButton type=submitltbuttongt lttdgt lttrgt
lttablegtltformgtltdiv id=resultgtltdivgt
checkbox $(checkbox)
Selects all elements of type checkbox
Added in version 10
$(checkbox)
$(checkbox) is equivalent to $([type=checkbox]) As with other pseudo-class selectors (thosethat begin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(checkbox) isequivalent to $(checkbox) so $(inputcheckbox) should be used instead
Example 1 Finds all checkbox inputs
Javascript
var input = $(form inputcheckbox)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height25px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=checkbox gt ltinput type=fi le gt ltinput type=hidden gt
ltinput type=image gt ltinput type=password gt ltinput type=radio gt
ltinput type=reset gt ltinput type=submit gt ltinput type=text gt
ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt
ltdivgt ltdivgt
radio $(radio)
Selects all elements of type radio
Added in version 10
$(radio)
$(radio) is equivalent to $([type=radio]) As with other pseudo-class selectors (those thatbegin with a ) it is recommended to precede it with a tag name or some other selectorotherwise the universal selector () is implied In other words the bare $(radio) is equivalentto $(radio) so $(inputradio) should be used instead
To select a set of associated radio buttons you might use $(input[name=gender]radio)
Example 1 Finds all radio inputs
Javascript
var input = $(form inputradio)wrap(ltspangtltspangt)parent()css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height25px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio name=asdf gt ltinput type=radio name=asdf gt
ltinput type=reset gt ltinput type=submit gt ltinput type=text gt
ltselectgtltoptiongtOptionltoptiongtltselectgt lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt
ltdivgt ltdivgt
password $(password)
Selects all elements of type password
Added in version 10
$(password)
$(password) is equivalent to $([type=password]) As with other pseudo-class selectors (thosethat begin with a ) it is recommended to precede it with a tag name or some other selector
otherwise the universal selector () is implied In other words the bare $(password) isequivalent to $(password) so $(inputpassword) should be used instead
Example 1 Finds all password inputs
Javascript
var input = $(inputpassword)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height45px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt
text $(text)
Selects all elements of type text
Added in version 10
$(text)
$(text ) is equivalent to $([type=text ]) and thus selects all ltinput type=textgt elements Aswith other pseudo-class selectors (those that begin with a ) it is recommended to precede itwith a tag name or some other selector otherwise the universal selector () is implied Inother words the bare $(text ) is equivalent to $(text ) so $(inputtext ) should be usedinstead
Note As of jQuery 152 text selects input elements that have no specif ied type at t ribute (inwhich case type=text is implied)
Example 1 Finds all text inputs
Javascript
var input = $(form inputtext)css(backgroundyellow border3px red solid) $(div)text(For this type jQuery found + inputlength + ) css(color red) $(form)submit(function () return false ) so it wont submit
CSS
textarea height25px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdivgt ltdivgt
input $(input)
Selects all input textarea select and button elements
Added in version 10
$(input)
The input selector basically selects all form controls
Example 1 Finds all input elements
Javascript
var all Inputs = $(input) var formChildren = $(form gt ) $(messages)text(Found + all Inputslength + inputs and the form has + formChildrenlength + children) so it wont submit $(form)submit(function () return false )
CSS
textarea height25px
HTML
ltformgt ltinput type=button value=Input Buttongt ltinput type=checkbox gt
ltinput type=fi le gt ltinput type=hidden gt ltinput type=image gt
ltinput type=password gt ltinput type=radio gt ltinput type=reset gt
ltinput type=submit gt ltinput type=text gt ltselectgtltoptiongtOptionltoptiongtltselectgt
lttextareagtlttextareagt ltbuttongtButtonltbuttongt ltformgt ltdiv id=messagesgt ltdivgt
only-child $(only-child)
Selects all elements that are the only child of their parent
Added in version 114
$(only-child)
If the parent has other child elements nothing is matched
Example 1 Change the text and add a border for each button that is the only child of its parent
Javascript
$(div buttononly-child)text(Alone)css(border 2px blue solid)
CSS
div width100px height80px margin5px floatleft backgroundb9e
HTML
ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongtltdivgt
ltdivgt ltbuttongtSiblingltbuttongtltdivgtltdivgt Noneltdivgt
ltdivgt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt ltbuttongtSiblingltbuttongt
ltdivgtltdivgt ltbuttongtSiblingltbuttongtltdivgt
last-child $(last-child)
Selects all elements that are the last child of their parent
Added in version 114
$(last-child)
While last matches only a single element last-child can match more than one one for eachparent
Example 1 Finds the last span in each matched div and adds some css plus a hover state
Javascript
$(div spanlast-child) css(colorred fontSize80) hover(function () $(this)addClass(solast) function () $(this)removeClass(solast) )
CSS
spansolast text-decorationl ine-through
HTML
ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt
ltspangtSamltspangt ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt
ltspangtRalphltspangt ltspangtDavidltspangt ltdivgt
first-child $(first-child)
Selects all elements that are the f irst child of their parent
Added in version 114
$(f irst-child)
While f irst matches only a single element the f irst-child selector can match more than oneone for each parent This is equivalent to nth-child(1)
Example 1 Finds the f irst span in each matched div to underline and add a hover state
Javascript
$(div spanfirst-child) css(text-decoration underline) hover(function () $(this)addClass(sogreen) function () $(this)removeClass(sogreen) )
CSS
span color008 spansogreen colorgreen font-weight bolder
HTML
ltdivgt ltspangtJohnltspangt ltspangtKarlltspangt ltspangtBrandonltspangt
ltdivgt ltdivgt ltspangtGlenltspangt ltspangtTaneltspangt ltspangtRalphltspangt
ltdivgt
nth-child $(nth-child(indexevenoddequation))
Selects all elements that are the nth-child of their parent
Added in version 114
$(nth-child(indexevenoddequat ion))
indexNumberString The index of each child to match start ing with 1 the string evenor odd or an equat ion ( eg nth-child(even) nth-child(4n) )
Because jQuerys implementat ion of nth-child(n) is strict ly derived from the CSS specif icat ionthe value of n is 1-indexed meaning that the count ing starts at 1 For all other selectorexpressions however jQuery follows JavaScript s 0-indexed count ing Therefore given asingle ltulgt containing two ltligts $(linth-child(1)) selects the f irst ltligt while $(lieq(1)) selectsthe second
The nth-child(n) pseudo-class is easily confused with eq(n) even though the two can result indramat ically dif ferent matched elements With nth-child(n) all children are counted regardlessof what they are and the specif ied element is selected only if it matches the selector at tachedto the pseudo-class With eq(n) only the selector at tached to the pseudo-class is counted notlimited to children of any other element and the (n+1)th one (n is 0-based) is selected
Further discussion of this unusual usage can be found in the W3C CSS specif icat ion
Example 1 Finds the second li in each matched ul and notes it
Javascript
$(ul l i nth-child(2))append(ltspangt - 2ndltspangt)
CSS
div floatleft span colorblue
HTML
ltdivgtltulgt ltligtJohnltligt ltligtKarlltl igt ltligtBrandonltligt
ltulgtltdivgt ltdivgtltulgt ltligtSamltligt ltulgtltdivgt
ltdivgtltulgt ltligtGlenltligt ltligtTaneltligt ltligtRalphltligt
ltligtDavidltligt ltulgtltdivgt
Example 2 This is a playground to see how the selector works with dif ferent strings Not icethat this is dif ferent f rom the even and odd which have no regard for parent and just f ilter thelist of elements to every other one The nth-child however counts the index of the child to itspart icular parent In any case it s easier to see than explain so
Javascript
$(button)cl ick(function () var str = $(this)text() $(tr)css(background white) $(tr + str)css(background ff0000) $(inner)text(str) )
CSS
button displayblock font-size12px width100px div floatleft margin10px font-size10px border1px solid black span colorblue font-size18px inner colorred td width50px text-aligncenter
HTML
ltdivgt ltbuttongtnth-child(even)ltbuttongt ltbuttongtnth-child(odd)ltbuttongt ltbuttongtnth-child(3n)ltbuttongt
ltbuttongtnth-child(2)ltbuttongt ltdivgt ltdivgt ltbuttongtnth-child(3n+1)ltbuttongt ltbuttongtnth-child(3n+2)ltbuttongt
ltbuttongtevenltbuttongt ltbuttongtoddltbuttongt ltdivgt ltdivgtlttablegt
lttrgtlttdgtJohnlttdgtlttrgt lttrgtlttdgtKarllttdgtlttrgt lttrgtlttdgtBrandonlttdgtlttrgt
lttrgtlttdgtBenjaminlttdgtlttrgt lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtSamlttdgtlttrgt
lttablegtltdivgt ltdivgtlttablegt lttrgtlttdgtGlenlttdgtlttrgt lttrgtlttdgtTanelttdgtlttrgt
lttrgtlttdgtRalphlttdgtlttrgt lttrgtlttdgtDavidlttdgtlttrgt lttrgtlttdgtMikelttdgtlttrgt
lttrgtlttdgtDanlttdgtlttrgt lttablegtltdivgt ltspangt trltspan id=innergtltspangt
ltspangt
attributeContainsPrefix $([attribute|=value])
Selects elements that have the specif ied at t ribute with a value either equal to a given string orstart ing with that string followed by a hyphen (-)
Added in version 10
$([at t ribute|=value])
attributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
This selector was introduced into the CSS specif icat ion to handle language at t ributes
Example 1 Finds all links with an href lang at t ribute that is english
Javascript
$(a[hreflang|=en])css(border3px dotted green)
HTML
lta href=examplehtml hreflang=engtSome textltagt
lta href=examplehtml hreflang=en-UKgtSome other textltagt
lta href=examplehtml hreflang=englishgtwill not be outl inedltagt
CSS
a display inl ine-block
attributeContainsWord $([attribute~=value])
Selects elements that have the specif ied at t ribute with a value containing a given worddelimited by spaces
Added in version 10
$([at t ribute~=value])
at t ributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
This selector matches the test string against each word in the at t ribute value where a word isdef ined as a string delimited by whitespace The selector matches if the test string is exact lyequal to any of the words
Example 1 Finds all inputs with a name attribute that contains the word man and sets the
value with some text
Javascript
$( input[name~=man])val(mr man is in it)
HTML
ltinput name=man-news gt
ltinput name=milk man gt ltinput name=letterman2 gt ltinput name=newmilk gt
attributeMultiple$([attributeFilter1][attributeFilter2][attributeFilterN])
Matches elements that match all of the specif ied at t ribute f ilters
Added in version 10
$([at t ributeFilter1][at t ributeFilter2][at t ributeFilterN])
at t ributeFilter1Selector An at t ribute f ilter
at t ributeFilter2Selector Another at t ribute f ilter reducing the select ion even more
attributeFilterNSelector (opt ional) As many more at t ribute f ilters as necessary
Example 1 Finds all inputs that have an id at t ribute and whose name attribute ends with manand sets the value
Javascript
$( input[id][name$=man])val(only this one)
HTML
ltinput id=man-news name=man-news gt
ltinput name=milkman gt ltinput id=letterman name=new-letterman gt ltinput name=newmilk gt
attributeContains $([attribute=value])
Selects elements that have the specif ied at t ribute with a value containing the a given substring
Added in version 10
$([at t ribute=value])
at t ributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
This is the most generous of the jQuery at t ribute selectors that match against a value It willselect an element if the selectors string appears anywhere within the element s at t ribute valueCompare this selector with the Attribute Contains Word selector (eg [at t r~=word]) which ismore appropriate in many cases
Example 1 Finds all inputs with a name attribute that contains man and sets the value withsome text
Javascript
$( input[name=man])val(has man in it)
HTML
ltinput name=man-news gt
ltinput name=milkman gt ltinput name=letterman2 gt ltinput name=newmilk gt
attributeEndsWith $([attribute$=value])
Selects elements that have the specif ied at t ribute with a value ending exact ly with a givenstring The comparison is case sensit ive
Added in version 10
$([at t ribute$=value])
at t ributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
Example 1 Finds all inputs with an at t ribute name that ends with let ter and puts text in them
Javascript
$( input[name$=letter])val(a letter)
HTML
ltinput name=newsletter gt
ltinput name=milkman gt ltinput name=jobletter gt
attributeStartsWith $([attribute^=value])
Selects elements that have the specif ied at t ribute with a value beginning exact ly with a givenstring
Added in version 10
$([at t ribute^=value])
at t ributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
This selector can be useful for ident ifying elements in pages produced by server-sideframeworks that produce HTML with systemat ic element IDs However it will be slower thanusing a class selector so leverage classes if you can to group like elements
Example 1 Finds all inputs with an at t ribute name that starts with news and puts text in them
Javascript
$( input[name^=news])val(news here)
HTML
ltinput name=newsletter gt
ltinput name=milkman gt ltinput name=newsboy gt
attributeNotEqual $([attribute=value])
Select elements that either dont have the specif ied at t ribute or do have the specif ied at t ributebut not with a certain value
Added in version 10
$([at t ribute=value])
at t ributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
This selector is equivalent to not([at t r=value])
Example 1 Finds all inputs that dont have the name newslet ter and appends text to the spannext to it
Javascript
$( input[name=newsletter])next()append(ltbgt not newsletterltbgt)
HTML
ltdivgt
ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtname is newsletterltspangt
ltdivgt ltdivgt ltinput type=radio value=Cold Fusion gt ltspangtno nameltspangt
ltdivgt ltdivgt ltinput type=radio name=accept value=Evil Plans gt
ltspangtname is acceptltspangt ltdivgt
attributeEquals $([attribute=value])
Selects elements that have the specif ied at t ribute with a value exact ly equal to a certain value
Added in version 10
$([at t ribute=value])
attributeString An at t ribute name
valueString An at t ribute value Quotes are mandatory
Example 1 Finds all inputs with a value of Hot Fuzz and changes the text of the next siblingspan
Javascript
$( input[value=Hot Fuzz])next()text( Hot Fuzz)
HTML
ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Hot Fuzz gt ltspangtnameltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Cold Fusion gt ltspangtvalueltspangt ltlabelgt ltdivgt ltdivgt ltlabelgt ltinput type=radio name=newsletter value=Evil Plans gt ltspangtvalueltspangt ltlabelgt ltdivgt
attributeHas $([attribute])
Selects elements that have the specif ied at t ribute with any value
Added in version 10
$([at t ribute])
at t ributeString An at t ribute name
Example 1 Bind a single click that adds the div id to its text
Javascript
$(div[id])one(cl ick function() var idString = $(this)text() + = + $(this)attr( id) $(this)text(idString) )
HTML
ltdivgtno idltdivgt ltdiv id=heygtwith idltdivgt
ltdiv id=theregthas an idltdivgt ltdivgtnopeltdivgt
visible $(visible)
Selects all elements that are visible
Added in version 10
$(visible)
Elements can be considered hidden for several reasons
They have a CSS display value of none
They are form elements with type=hidden
Their width and height are explicit ly set to 0
An ancestor element is hidden so the element is not shown on the page
Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start at the animat ion
How visible is calculated was changed in jQuery 132 The release notes out line the changes inmore detail
Example 1 Make all visible divs turn yellow on click
Javascript
$(divvisible)cl ick(function () $(this)css(background yellow) ) $(button)cl ick(function () $(divhidden)show(fast) )
CSS
div width50px height40px margin5px border3px outset green floatleft starthidden displaynone
HTML
ltbuttongtShow hidden to see they dont changeltbuttongt ltdivgtltdivgt ltdiv class=starthiddengtltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdiv style=displaynonegtltdivgt
hidden $(hidden)
Selects all elements that are hidden
Added in version 10
$(hidden)
Elements can be considered hidden for several reasons
They have a CSS display value of none
They are form elements with type=hidden
Their width and height are explicit ly set to 0
An ancestor element is hidden so the element is not shown on the page
Elements with visibility hidden or opacity 0 are considered to be visible since they st ill consumespace in the layout During animat ions that hide an element the element is considered to bevisible unt il the end of the animat ion During animat ions to show an element the element isconsidered to be visible at the start of the animat ion
How hidden is determined was changed in jQuery 132 An element is assumed to be hidden if itor any of its parents consumes no space in the document CSS visibility isnt taken into account(therefore $(elem)css(visibilityhidden)is(hidden) == false) The release notes out line thechanges in more detail
Example 1 Shows all hidden divs and counts hidden inputs
Javascript
in some browsers hidden includes head title script etcvar hiddenEls = $(body)find(hidden)not(script)
$(spanfirst)text(Found + hiddenElslength + hidden elements total)$(divhidden)show(3000)$(spanlast)text(Found + $(inputhidden)length + hidden inputs)
CSS
div width70px height40px backgroundee77ff margin5px floatleft span displayblock clearleft colorred starthidden displaynone
HTML
ltspangtltspangt ltdivgtltdivgt ltdiv style=displaynonegtHiderltdivgt ltdivgtltdivgt
ltdiv class=starthiddengtHiderltdivgt ltdivgtltdivgt ltformgt ltinput type=hidden gt
ltinput type=hidden gt ltinput type=hidden gt ltformgt ltspangt
ltspangt
parent $(parent)
Select all elements that are the parent of another element including text nodes
Added in version 10
$(parent)
This is the inverse of empty
One important thing to note regarding the use of parent (and empty) is that child elementsinclude text nodes
The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elements
on the other hand are empty (ie have no children) by def init ion ltinputgt ltimggt ltbrgt and lthrgtfor example
Example 1 Finds all tds with children including text
Javascript
$(tdparent)fadeTo(1500 03)
CSS
td width40px backgroundgreen
HTML
lttable border=1gt
lttrgtlttdgtValue 1lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtValue 2lttdgtlttdgtlttdgtlttrgt
lttablegt
has $(has(selector))
Selects elements which contain at least one element that matches the specif ied selector
Added in version 114
$(has(selector))
selectorSelector Any selector
The expression $(divhas(p)) matches a ltdivgt if a ltpgt exists anywhere among its descendantsnot just as a direct child
Example 1 Adds the class test to all divs that have a paragraph inside of them
Javascript
$(divhas(p))addClass(test)
HTML
ltdivgtltpgtHello in a paragraphltpgtltdivgt
ltdivgtHello again (with no paragraph)ltdivgt
CSS
test border 3px inset red
empty $(empty)
Select all elements that have no children (including text nodes)
Added in version 10
$(empty)
This is the inverse of parent
One important thing to note with empty (and parent) is that child elements include text nodes
The W3C recommends that the ltpgt element have at least one child node even if that child ismerely text (see ht tpwwww3orgTRhtml401struct text htmledef-P) Some other elementson the other hand are empty (ie have no children) by def init ion and
for example
Example 1 Finds all elements that are empty - they dont have child elements or text
Javascript
$(tdempty)text(Was empty)css(background rgb(255220200))
CSS
td text-aligncenter
HTML
lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtlttdgtlttrgt lttrgtlttdgtTD 2lttdgtlttdgtlttdgtlttrgt
lttrgtlttdgtlttdgtlttdgtTD5lttdgtlttrgt lttablegt
contains $(contains(text))
Select all elements that contain the specif ied text
Added in version 114
$(contains(text))
text String A string of text to look for It s case sensit ive
The matching text can appear direct ly within the selected element in any of that element sdescendants or a combinat ion thereof As with at t ribute value selectors text inside theparentheses of contains() can be writ ten as bare words or surrounded by quotat ion marks Thetext must have matching case to be selected
Example 1 Finds all divs containing John and underlines them
Javascript
$(divcontains( John))css(text-decoration underline)
HTML
ltdivgtJohn Resigltdivgt
ltdivgtGeorge MartinltdivgtltdivgtMalcom John SinclairltdivgtltdivgtJ Ohnltdivgt
animated $(animated)
Select all elements that are in the progress of an animat ion at the t ime the selector is run
Added in version 12
$(animated)
Example 1 Change the color of any div that is animated
Javascript
$(run)cl ick(function() $(divanimated)toggleClass(colored) ) function animateIt() $(mover)sl ideToggle(slow animateIt) animateIt()
HTML
ltbutton id=rungtRunltbuttongt
ltdivgtltdivgt ltdiv id=movergtltdivgt ltdivgtltdivgt
CSS
div backgroundyellow border1px solid AAA width80px height80px margin0 5px floatleft divcolored backgroundgreen
header $(header)
Selects all elements that are headers like h1 h2 h3 and so on
Added in version 12
$(header)
Example 1 Adds a background and text color to all the headers on the page
Javascript
$(header)css( backgroundCCC colorblue )
HTML
lth1gtHeader 1lth1gt
ltpgtContents 1ltpgt lth2gtHeader 2lth2gt ltpgtContents 2ltpgt
CSS
body font-size 10px font-family Arial h1 h2 margin 3px 0
lt $(lt(index))
Select all elements at an index less than index within the matched set
Added in version 10
$(lt (index))
indexNumber Zero-based index
index-related selectors
The index-related selectors (including this less than selector) f ilter the set of elements thathave matched the expressions that precede them They narrow the set down based on theorder of the elements within this matched set For example if elements are f irst selected with aclass selector (myclass) and four elements are returned these elements are given indices 0through 3 for the purposes of these selectors
Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasslt (1)) selects the f irst element in the document with the class myclass ratherthan select ing no elements In contrast nth-child(n) uses 1-based indexing to conform to theCSS specif icat ion
Example 1 Finds TDs less than the one with the 4th index (TD4)
Javascript
$(tdlt(4))css(color red)
HTML
lttable border=1gt
lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt
lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt
gt $(gt(index))
Select all elements at an index greater than index within the matched set
Added in version 10
$(gt(index))
indexNumber Zero-based index
index-related selectors
The index-related selector expressions (including this greater than selector) f ilter the set ofelements that have matched the expressions that precede them They narrow the set downbased on the order of the elements within this matched set For example if elements are f irstselected with a class selector (myclass) and four elements are returned these elements aregiven indices 0 through 3 for the purposes of these selectors
Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclassgt(1)) selects elements af ter the second element in the document with theclass myclass rather than af ter the f irst In contrast nth-child(n) uses 1-based indexing toconform to the CSS specif icat ion
Example 1 Finds TD 5 and higher Reminder the indexing starts at 0
Javascript
$(tdgt(4))css(text-decoration l ine-through)
HTML
lttable border=1gt
lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt
lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgt lttablegt
eq $(eq(index))
Select the element at index n within the matched set
Added in version 10
$(eq(index))
indexNumber Zero-based index of the element to match
The index-related selectors (eq() lt () gt() even odd) f ilter the set of elements that havematched the expressions that precede them They narrow the set down based on the order ofthe elements within this matched set For example if elements are f irst selected with a classselector (myclass) and four elements are returned these elements are given indices 0 through3 for the purposes of these selectors
Note that since JavaScript arrays use 0-based indexing these selectors ref lect that fact This iswhy $(myclasseq(1)) selects the second element in the document with the class myclassrather than the f irst In contrast nth-child(n) uses 1-based indexing to conform to the CSSspecif icat ion
Unlike the eq(index) method the eq(index) selector does not accept a negat ive value for indexFor example while $(li)eq(-1) selects the last li element $(lieq(-1)) selects nothing
Example 1 Finds the third td
Javascript
$(tdeq(2))css(color red)
HTML
lttable border=1gt lttrgtlttdgtTD 0lttdgtlttdgtTD 1lttdgtlttdgtTD 2lttdgtlttrgt lttrgtlttdgtTD 3lttdgtlttdgtTD 4lttdgtlttdgtTD 5lttdgtlttrgt lttrgtlttdgtTD 6lttdgtlttdgtTD 7lttdgtlttdgtTD 8lttdgtlttrgtlttablegt
Example 2 Apply three dif ferent styles to list items to demonstrate that eq() is designed toselect a single element while nth-child() or eq() within a looping construct such as each() canselect mult iple elements
Javascript
applies yellow background color to a single ltligt$(ulnav l i eq(1))css( backgroundColor ff0 )
applies ital ics to text of the second ltligt within each ltul class=navgt$(ulnav)each(function(index) $(this)find(l i eq(1))css( fontStyle ital ic ))
applies red text color to descendants of ltul class=navgt for each ltligt that is the second child of its parent$(ulnav l i nth-child(2))css( color red )
HTML
ltul class=navgt ltligtList 1 item 1ltligt ltligtList 1 item 2ltligt ltligtList 1 item 3ltligtltulgtltul class=navgt ltligtList 2 item 1ltligt ltligtList 2 item 2ltligt ltligtList 2 item 3ltligtltulgt
odd $(odd)
Selects odd elements zero-indexed See also even
Added in version 10
$(odd)
In part icular note that the 0-based indexing means that counter-intuit ively odd selects thesecond element fourth element and so on within the matched set
Example 1 Finds odd table rows matching the second fourth and so on (index 1 3 5 etc)
Javascript
$(trodd)css(background-color bbbbff)
CSS
table backgroundf3f7f5
HTML
lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt
lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt
even $(even)
Selects even elements zero-indexed See also odd
Added in version 10
$(even)
In part icular note that the 0-based indexing means that counter-intuit ively even selects thef irst element third element and so on within the matched set
Example 1 Finds even table rows matching the f irst third and so on (index 0 2 4 etc)
Javascript
$(treven)css(background-color bbbbff)
CSS
table backgroundeeeeee
HTML
lttable border=1gt lttrgtlttdgtRow with Index 0lttdgtlttrgt lttrgtlttdgtRow with Index 1lttdgtlttrgt
lttrgtlttdgtRow with Index 2lttdgtlttrgt lttrgtlttdgtRow with Index 3lttdgtlttrgt lttablegt
not $(not(selector))
Selects all elements that do not match the given selector
Added in version 10
$(not(selector))
selectorSelector A selector with which to f ilter by
All selectors are accepted inside not() for example not(div a) and not(diva)
Additional Notes
The not() method will end up providing you with more readable select ions than pushingcomplex selectors or variables into a not() selector f ilter In most cases it is a better choice
Example 1 Finds all inputs that are not checked and highlights the next sibling span Not icethere is no change when clicking the checkboxes since no click events have been linked
Javascript
$(inputnot(checked) + span)css(background-color yellow) $(input)attr(disabled disabled)
HTML
ltdivgt ltinput type=checkbox name=a gt ltspangtMaryltspangtltdivgt
ltdivgt ltinput type=checkbox name=b gt ltspangtlcmltspangt
ltdivgtltdivgt ltinput type=checkbox name=c checked=checked gt
ltspangtPeterltspangtltdivgt
last $(last)
Selects the last matched element
Added in version 10
$(last)
Note that last selects a single element by f iltering the current jQuery collect ion and matchingthe last element within it
Example 1 Finds the last table row
Javascript
$(trlast)css(backgroundColor yellow fontWeight bolder)
HTML
lttablegt
lttrgtlttdgtFirst Rowlttdgtlttrgt lttrgtlttdgtMiddle Rowlttdgtlttrgt lttrgtlttdgtLast Rowlttdgtlttrgt
lttablegt
first $(first)
Selects the f irst matched element
Added in version 10
$(f irst)
The f irst pseudo-class is equivalent to eq(0) It could also be writ ten as lt (1) While thismatches only a single element f irst-child can match more than one One for each parent
Example 1 Finds the f irst table row
Javascript
$(trfirst)css(font-style ital ic)
CSS
td colorblue font-weightbold
HTML
lttablegt lttrgtlttdgtRow 1lttdgtlttrgt lttrgtlttdgtRow 2lttdgtlttrgt
lttrgtlttdgtRow 3lttdgtlttrgt lttablegt
next siblings $(prev ~ siblings)
Selects all sibling elements that follow af ter the prev element have the same parent andmatch the f iltering siblings selector
Added in version 10
$(prev ~ siblings)
prevSelector Any valid selector
siblingsSelector A selector to f ilter elements that are the following siblings of the f irstselector
The notable dif ference between (prev + next) and (prev ~ siblings) is their respect ive reachWhile the former reaches only to the immediately following sibling element the lat ter extendsthat reach to all following sibling elements
Example 1 Finds all divs that are siblings af ter the element with prev as its id Not ice the spanisnt selected since it is not a div and the niece isnt selected since it is a child of a sibling notan actual sibling
Javascript
$(prev ~ div)css(border 3px groove blue)
CSS
divspan displayblock width80px height80px margin5px backgroundbbffaa floatleft font-size14px divsmall width60px height25px font-size12px backgroundfab
HTML
ltdivgtdiv (doesnt match since before prev)ltdivgt ltspan id=prevgtspanprevltspangt ltdivgtdiv siblingltdivgt
ltdivgtdiv sibling ltdiv id=smallgtdiv nieceltdivgtltdivgt ltspangtspan sibling (not div)ltspangt ltdivgtdiv siblingltdivgt
next adjacent $(prev + next)
Selects all next elements matching next that are immediately preceded by a sibling prev
Added in version 10
$(prev + next)
prevSelector Any valid selector
nextSelector A selector to match the element that is next to the f irst selector
One important point to consider with both the next adjacent sibling selector (prev + next) andthe general sibling selector (prev ~ siblings) is that the elements on either side of thecombinator must share the same parent
Example 1 Finds all inputs that are next to a label
Javascript
$(label + input)css(color blue)val(Labeled)
HTML
ltformgt
ltlabelgtNameltlabelgt ltinput name=name gt ltfieldsetgt ltlabelgtNewsletterltlabelgt
ltinput name=newsletter gt ltfieldsetgt ltformgt ltinput name=none gt
child $(parent gt child)
Selects all direct child elements specif ied by child of elements specif ied by parent
Added in version 10
$(parent gt child)
parentSelector Any valid selector
childSelector A selector to f ilter the child elements
As a CSS selector the child combinator is supported by all modern web browsers includingSafari Firefox Opera Chrome and Internet Explorer 7 and above but notably not by InternetExplorer versions 6 and below However in jQuery this selector (along with all others) worksacross all supported browsers including IE6
The child combinator (E gt F) can be thought of as a more specif ic form of the descendantcombinator (E F) in that it selects only f irst-level descendants
Note The $(gt elem context) selector will be deprecated in a future release Itsusage is thus discouraged in lieu of using alternative selectors
Example 1 Places a border around all list items that are children of
Javascript
$(ultopnav gt l i)css(border 3px double red)
CSS
body font-size14px
HTML
ltul class=topnavgt ltligtItem 1ltligt ltligtItem 2 ltulgtltligtNested item 1ltligtltligtNested item 2ltligtltligtNested item 3ltligtltulgt ltl igt ltligtItem 3ltligtltulgt
descendant $(ancestor descendant)
Selects all elements that are descendants of a given ancestor
Added in version 10
$(ancestor descendant)
ancestorSelector Any valid selector
descendantSelector A selector to f ilter the descendant elements
A descendant of an element could be a child grandchild great-grandchild and so on of thatelement
Example 1 Finds all input descendants of forms
Javascript
$(form input)css(border 2px dotted blue)
CSS
body font-size14px form border2px green solid padding2px margin0 backgroundefe div colorred fieldset margin1px padding3px
HTML
ltformgt ltdivgtForm is surrounded by the green outl ineltdivgt ltlabelgtChildltlabelgt ltinput name=name gt
ltfieldsetgt ltlabelgtGrandchildltlabelgt ltinput name=newsletter gt ltfieldsetgt
ltformgt Sibling to form ltinput name=none gt
multiple $(selector1 selector2 selectorN)
Selects the combined results of all the specif ied selectors
Added in version 10
$(selector1 selector2 selectorN)
selector1Selector Any valid selector
selector2Selector Another valid selector
selectorNSelector (opt ional) As many more valid selectors as you like
You can specify any number of selectors to combine into a single result This mult ipleexpression combinator is an ef f icient way to select disparate elements The order of the DOMelements in the returned jQuery object may not be ident ical as they will be in document orderAn alternat ive to this combinator is the add() method
Example 1 Finds the elements that match any of these three selectors
Javascript
$(divspanpmyClass)css(border3px solid red)
HTML
ltdivgtdivltdivgt
ltp class=myClassgtp class=myClassltpgt ltp class=notMyClassgtp class=notMyClassltpgt ltspangtspanltspangt
CSS
divspanp width 126px height 60px floatleft padding 3px margin 2px background-color EEEEEE font-size14px
Example 2 Show the order in the jQuery object
Javascript
var l ist = $(divpspan)map(function () return thistagName )get()join( ) $(b)append(documentcreateTextNode(list))
CSS
b colorred font-size16px displayblock clearleft divspanp width 40px height 40px floatleft margin 10px background-color blue padding3px colorwhite
HTML
ltspangtspanltspangt
ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt ltspangtspanltspangt
ltpgtpltpgt ltdivgtdivltdivgt ltbgtltbgt
all $()
Selects all elements
Added in version 10
$()
Caut ion The all or universal selector is extremely slow except when used by itself
Example 1 Finds every element (including head body etc) in the document
Javascript
var elementCount = $()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)
HTML
ltdivgtDIVltdivgt
ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgt
CSS
h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE
Example 2 A common way to select all elements is to f ind within documentbody so elementslike head script etc are lef t out
Javascript
var elementCount = $(test)find()css(border3px solid red)length$(body)prepend(lth3gt + elementCount + elements foundlth3gt)
HTML
ltdiv id=testgt ltdivgtDIVltdivgt ltspangtSPANltspangt ltpgtP ltbuttongtButtonltbuttongtltpgtltdivgt
CSS
h3 margin 0 divspanp width 80px height 40px floatleft padding 10px margin 10px background-color EEEEEE test width auto height auto background-color transparent
class $(class)
Selects all elements with the given class
Added in version 10
$(class)
classString A class to search for An element can have mult iple classes only one ofthem must match
For class selectors jQuery uses JavaScript s nat ive getElementsByClassName() funct ion if thebrowser supports it
Example 1 Finds the element with the class myClass
Javascript
$(myClass)css(border3px solid red)
HTML
ltdiv class=notMegtdiv class=notMeltdivgt
ltdiv class=myClassgtdiv class=myClassltdivgt ltspan class=myClassgtspan class=myClassltspangt
CSS
divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE
Example 2 Finds the element with both myclass and otherclass classes
Javascript
$(myclassotherclass)css(border13px solid red)
HTML
ltdiv class=myclassgtdiv class=notMeltdivgt
ltdiv class=myclass otherclassgtdiv class=myClassltdivgt ltspan class=myclass otherclassgtspan class=myClassltspangt
CSS
divspan width 100px height 40px floatleft padding 10px margin 10px background-color EEEEEE
element $(element)
Selects all elements with the given tag name
Added in version 10
$(element)
elementString An element to search for Refers to the tagName of DOM nodes
JavaScript s getElementsByTagName() funct ion is called to return the appropriate elementswhen this expression is used
Example 1 Finds every DIV element
Javascript
$(div)css(border9px solid red)
HTML
ltdivgtDIV1ltdivgt
ltdivgtDIV2ltdivgt ltspangtSPANltspangt
CSS
divspan width 60px height 60px floatleft padding 10px margin 10px background-color EEEEEE
id $(id)
Selects a single element with the given id at t ribute
Added in version 10
$( id)
idString An ID to search for specif ied via the id at t ribute of an element
For id selectors jQuery uses the JavaScript funct ion documentgetElementById() which isextremely ef f icient When another selector is at tached to the id selector such as h2pageTit lejQuery performs an addit ional check before ident ifying the element as a match
As always remember that as a developer your time is typically the most valuableresource Do not focus on optimization of selector speed unless it is clear thatperformance needs to be improved
Each id value must be used only once within a document If more than one element has beenassigned the same ID queries that use that ID will only select the f irst matched element in theDOM This behavior should not be relied on however a document with more than one elementusing the same ID is invalid
If the id contains characters like periods or colons you have to escape those characters withbackslashes
Example 1 Finds the element with the id myDiv
Javascript
$(myDiv)css(border3px solid red)
HTML
ltdiv id=notMegtltpgtid=notMeltpgtltdivgt
ltdiv id=myDivgtid=myDivltdivgt
CSS
div width 90px height 90px floatleft padding 5px margin 5px background-color EEEEEE
Example 2 Finds the element with the id myIDentry[1] See how certain characters must beescaped with backslashes
Javascript
$(myIDentry[1])css(border3px solid red)
HTML
ltdiv id=myIDentry[0]gtid=myIDentry[0]ltdivgt
ltdiv id=myIDentry[1]gtid=myIDentry[1]ltdivgt ltdiv id=myIDentry[2]gtid=myIDentry[2]ltdivgt
CSS
div width 300px floatleft padding 2px margin 3px background-color EEEEEE
Traversing
has
Reduce the set of matched elements to those that have a descendant that matches theselector or DOM element
Added in version 14
has(contained)jQuery
containedElement A DOM element to match elements against
Given a jQuery object that represents a set of DOM elements the has() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst the descendants of the matching elements the element will be included in the result ifany of its descendant elements matches the selector
Consider a page with a nested list as follows
ltulgt ltligtlist item 1ltligt ltligtlist item 2 ltulgt ltligtlist item 2-altligt ltligtlist item 2-bltligt ltulgt ltl igt ltligtlist item 3ltligt ltligtlist item 4ltligtltulgt
We can apply this method to the set of list items as follows
$( l i )has(ul )css(background-color red)
The result of this call is a red background for item 2 as it is the only ltligt that has a ltulgt amongits descendants
Example 1 Check if an element is inside another
Javascript
$(ul)append(ltligt + ($(ul)has(l i)length Yes No) + ltl igt) $(ul)has(l i)addClass(full)
CSS
ful l border 1px solid red
HTML
ltulgtltligtDoes the UL contain an LIltl igtltulgt
parentsUntil
Get the ancestors of each element in the current set of matched elements up to but notincluding the element matched by the selector DOM node or jQuery object
Added in version 16
parentsUnt il(element f ilter)jQuery
elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching ancestor elements
f ilterSelector (opt ional) A string containing a selector expression to matchelements against
Given a selector expression that represents a set of DOM elements the parentsUnt il() methodtraverses through the ancestors of these elements unt il it reaches an element matched by theselector passed in the methods argument The result ing jQuery object contains all of theancestors up to but not including the one matched by the parentsUnt il() selector
If the selector is not matched or is not supplied all ancestors will be selected in these cases itselects the same elements as the parents() method does when no selector is provided
As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstparentsUnt il() argument
The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it
Example 1 Find the ancestors of
up to
and give them a red background color Also f ind ancestors of
that have a class of yes up toand give them a green border
Javascript
$(l i item-a)parentsUntil(level-1) css(background-color red)
$(l i item-2)parentsUntil( $(ullevel-1) yes ) css(border 3px solid green)
HTML
ltul class=level-1 yesgt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2 yesgt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
prevUntil
Get all preceding siblings of each element up to but not including the element matched by theselector DOM node or jQuery object
Added in version 16
prevUnt il(element f ilter)jQuery
elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching preceding sibling elements
f ilterSelector (opt ional) A string containing a selector expression to matchelements against
Given a selector expression that represents a set of DOM elements the prevUnt il() methodsearches through the predecessors of these elements in the DOM tree stopping when itreaches an element matched by the methods argument The new jQuery object that isreturned contains all previous siblings up to but not including the one matched by theprevUnt il() selector the elements are returned in order f rom the closest sibling to the farthest
If the selector is not matched or is not supplied all previous siblings will be selected in thesecases it selects the same elements as the prevAll() method does when no f ilter selector isprovided
As of jQuery 16 A DOM node or jQuery object instead of a selector may be used for the f irstprevUnt il() argument
The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it
Example 1 Find the siblings that precede
up to the precedingand give them a red background color Also f ind previous
siblings ofup toand give them a green text color
Javascript
$(term-2)prevUntil(dt) css(background-color red) var term1 = documentgetElementById(term-1)$(term-3)prevUntil(term1 dd) css(color green)
HTML
ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt
ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt
ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt
nextUntil
Get all following siblings of each element up to but not including the element matched by theselector DOM node or jQuery object passed
Added in version 16
nextUnt il(element f ilter)jQuery
elementElement (opt ional) A DOM node or jQuery object indicat ing where to stopmatching following sibling elements
f ilterSelector (opt ional) A string containing a selector expression to matchelements against
Given a selector expression that represents a set of DOM elements the nextUnt il() methodsearches through the successors of these elements in the DOM tree stopping when it reachesan element matched by the methods argument The new jQuery object that is returnedcontains all following siblings up to but not including the one matched by the nextUnt il()argument
If the selector is not matched or is not supplied all following siblings will be selected in thesecases it selects the same elements as the nextAll() method does when no f ilter selector isprovided
As of jQuery 16 A DOM node or jQuery object instead of a selector may be passed to thenextUnt il() method
The method opt ionally accepts a selector expression for its second argument If this argumentis supplied the elements will be f iltered by test ing whether they match it
Example 1 Find the siblings that follow
up to the nextand give them a red background color Also f ind
siblings that followup toand give them a green text color
Javascript
$(term-2)nextUntil(dt) css(background-color red)
var term3 = documentgetElementById(term-3)$(term-1)nextUntil(term3 dd) css(color green)
HTML
ltdlgt ltdt id=term-1gtterm 1ltdtgt ltddgtdefinition 1-altddgt ltddgtdefinition 1-bltddgt ltddgtdefinition 1-cltddgt ltddgtdefinition 1-dltddgt
ltdt id=term-2gtterm 2ltdtgt ltddgtdefinition 2-altddgt ltddgtdefinition 2-bltddgt ltddgtdefinition 2-cltddgt
ltdt id=term-3gtterm 3ltdtgt ltddgtdefinition 3-altddgt ltddgtdefinition 3-bltddgtltdlgt
each
Iterate over a jQuery object execut ing a funct ion for each matched element
Added in version 10
each(funct ion(index Element))jQuery
funct ion(index Element)Funct ion A funct ion to execute for each matched element
The each() method is designed to make DOM looping constructs concise and less error-proneWhen called it iterates over the DOM elements that are part of the jQuery object Each t ime thecallback runs it is passed the current loop iterat ion beginning from 0 More important ly thecallback is f ired in the context of the current DOM element so the keyword this refers to theelement
Suppose we had a simple unordered list on the page
ltulgt ltligtfooltligt ltligtbarltligt ltulgt
We can select the list items and iterate across them
$( l i )each(function(index) alert(index + + $(this)text()) )
A message is thus alerted for each item in the list
0 foo
1 bar
We can stop the loop from within the callback funct ion by returning false
Example 1 Iterates over three divs and sets their color property
Javascript
$(documentbody)cl ick(function () $(div)each(function (i) i f (thisstylecolor = blue) thisstylecolor = blue else thisstylecolor = ) )
CSS
div colorred text-aligncenter cursorpointer font-weightbolder width300px
HTML
ltdivgtClick hereltdivgt
ltdivgtto iterate throughltdivgt ltdivgtthese divsltdivgt
Example 2 If you want to have the jQuery object instead of the regular DOM element use the$(this) funct ion for example
Javascript
$(span)cl ick(function () $(l i)each(function() $(this)toggleClass(example) ) )
CSS
ul font-size18px margin0 span colorblue text-decorationunderline cursorpointer example font-styleital ic
HTML
To do l ist ltspangt(click here to change)ltspangt ltulgt ltligtEatltligt ltligtSleepltligt
ltligtBe merryltligt ltulgt
Example 3 You can use return to break out of each() loops early
Javascript
$(button)cl ick(function () $(div)each(function (index domEle) domEle == this $(domEle)css(backgroundColor yellow) i f ($(this)is(stop)) $(span)text(Stopped at div index + index) return false ) )
CSS
div width40px height40px margin5px floatleft border2px blue solid text-aligncenter span colorred
HTML
ltbuttongtChange colorsltbuttongt ltspangtltspangt ltdivgtltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt ltdiv id=stopgtStop hereltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt
first
Reduce the set of matched elements to the f irst in the set
Added in version 14
f irst()jQuery
[
Given a jQuery object that represents a set of DOM elements the f irst() method constructs anew jQuery object f rom the f irst matching element
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
We can apply this method to the set of list items
$( l i )first()css(background-color red)
The result of this call is a red background for the f irst item
Example 1 Highlight the f irst span in a paragraph
CSS
highlightbackground-color yellow
Javascript
$(p span)first()addClass(highlight)
HTML
ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt
last
Reduce the set of matched elements to the f inal one in the set
Added in version 14
last()jQuery
[
Given a jQuery object that represents a set of DOM elements the last() method constructs anew jQuery object f rom the last matching element
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
We can apply this method to the set of list items
$( l i )last()css(background-color red)
The result of this call is a red background for the f inal item
Example 1 Highlight the last span in a paragraph
CSS
highlightbackground-color yellow
Javascript
$(p span)last()addClass(highlight)
HTML
ltpgtltspangtLookltspangt ltspangtThis is some text in a paragraphltspangt ltspangtThis is a note about itltspangtltpgt
slice
Reduce the set of matched elements to a subset specif ied by a range of indices
Added in version 114
slice(start end)jQuery
start Integer An integer indicat ing the 0-based posit ion at which the elements begin tobe selected If negat ive it indicates an of fset f rom the end of the set
endInteger (opt ional) An integer indicat ing the 0-based posit ion at which theelements stop being selected If negat ive it indicates an of fset f rom theend of the set If omit ted the range cont inues unt il the end of the set
Given a jQuery object that represents a set of DOM elements the slice() method constructs anew jQuery object f rom a subset of the matching elements The supplied start index ident if iesthe posit ion of one of the elements in the set if end is omit ted all elements af ter this one willbe included in the result
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
We can apply this method to the set of list items
$( l i )sl ice(2)css(background-color red)
The result of this call is a red background for items 3 4 and 5 Note that the supplied index iszero-based and refers to the posit ion of elements within the jQuery object not within theDOM tree
The end parameter allows us to limit the selected range even further For example
$( l i )sl ice(2 4)css(background-color red)
Now only items 3 and 4 are selected The index is once again zero-based the range extends upto but not including the specif ied index
Negative Indices
The jQuery slice() method is patterned af ter the JavaScript slice() method for arrays One ofthe features that it mimics is the ability for negat ive numbers to be passed as either the start orend parameter If a negat ive number is provided this indicates a posit ion start ing f rom the endof the set rather than the beginning For example
$( l i )sl ice(-2 -1)css(background-color red)
This t ime only list item 4 is turned red since it is the only item in the range between two fromthe end (-2) and one from the end (-1)
Example 1 Turns divs yellow based on a random slice
Javascript
function colorEm() var $div = $(div) var start = Mathfloor(Mathrandom() $divlength) var end = Mathfloor(Mathrandom() ($divlength - start)) + start + 1 i f (end == $divlength) end = undefined $divcss(background ) i f (end) $divsl ice(start end)css(background yellow) else $divsl ice(start)css(background yellow) $(span)text($(div)sl ice( + start + (end + end ) + )css(background yellow))
$(button)cl ick(colorEm)
CSS
div width40px height40px margin10px floatleft border2px solid blue span colorred font-weightbold button margin5px
HTML
ltpgtltbuttongtTurn sl ice yellowltbuttongt ltspangtClick the buttonltspangtltpgt ltdivgtltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt
Example 2 Selects all paragraphs then slices the select ion to include only the f irst element
Javascript
$(p)sl ice(0 1)wrapInner(ltbgtltbgt)
Example 3 Selects all paragraphs then slices the select ion to include only the f irst and secondelement
Javascript
$(p)sl ice(0 2)wrapInner(ltbgtltbgt)
Example 4 Selects all paragraphs then slices the select ion to include only the second element
Javascript
$(p)sl ice(1 2)wrapInner(ltbgtltbgt)
Example 5 Selects all paragraphs then slices the select ion to include only the second and thirdelement
Javascript
$(p)sl ice(1)wrapInner(ltbgtltbgt)
Example 6 Selects all paragraphs then slices the select ion to include only the third element
Javascript
$(p)sl ice(-1)wrapInner(ltbgtltbgt)
end
End the most recent f iltering operat ion in the current chain and return the set of matchedelements to its previous state
Added in version 10
end()jQuery
Most of jQuerys DOM traversal methods operate on a jQuery object instance and produce anew one matching a dif ferent set of DOM elements When this happens it is as if the new setof elements is pushed onto a stack that is maintained inside the object Each successivef iltering method pushes a new element set onto the stack If we need an older element set wecan use end() to pop the sets back of f of the stack
Suppose we have a couple short lists on a page
ltul class=firstgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgtltul class=secondgt ltli class=foogtlist item 1ltligt ltligtlist item 2ltligt ltli class=bargtlist item 3ltligtltulgt
The end() method is useful primarily when exploit ing jQuerys chaining propert ies When notusing chaining we can usually just call up a previous object by variable name so we dont needto manipulate the stack With end() though we can string all the method calls together
$(ulfirst)find(foo)css(background-color red) end()find(bar)css(background-color green)
This chain searches for items with the class foo within the f irst list only and turns theirbackgrounds red Then end() returns the object to its state before the call to f ind() so thesecond f ind() looks for bar inside ltul class=f irstgt not just inside that list s ltli class=foogtand turns the matching elements backgrounds green The net result is that items 1 and 3 ofthe f irst list have a colored background and none of the items from the second list do
A long jQuery chain can be visualized as a structured code block with f iltering methodsproviding the openings of nested blocks and end() methods closing them
$(ulfirst)find(foo) css(background-color red)end()find(bar) css(background-color green)end()
The last end() is unnecessary as we are discarding the jQuery object immediately thereafterHowever when the code is writ ten in this form the end() provides visual symmetry and a senseof complet ion acirceurordquomaking the program at least to the eyes of some developers more readableat the cost of a slight hit to performance as it is an addit ional funct ion call
Example 1 Selects all paragraphs f inds span elements inside these and reverts the select ionback to the paragraphs
Javascript
jQueryfnshowTags = function (n) var tags = thismap(function () return thistagName ) get()join( ) $(beq( + n + ))text(tags) return this
$(p)showTags(0) find(span) showTags(1) css(background yellow) end() showTags(2) css(font-style ital ic)
CSS
p div margin1px padding1px font-weightbold font-size16px div colorblue b colorred
HTML
ltpgt Hi there ltspangthowltspangt are you ltspangtdoingltspangt ltpgt
ltpgt This ltspangtspanltspangt is one of several ltspangtspansltspangt in this ltspangtsentenceltspangt ltpgt
ltdivgt Tags in jQuery object initial ly ltbgtltbgt ltdivgt ltdivgt Tags in jQuery object after find ltbgtltbgt
ltdivgt ltdivgt Tags in jQuery object after end ltbgtltbgt ltdivgt
Example 2 Selects all paragraphs f inds span elements inside these and reverts the select ion
back to the paragraphs
Javascript
$(p)find(span)end()css(border 2px red solid)
CSS
p margin10px padding10px
HTML
ltpgtltspangtHelloltspangt how are youltpgt
andSelf
Add the previous set of elements on the stack to the current set
Added in version 12
andSelf()jQuery
As described in the discussion for end() jQuery objects maintain an internal stack that keepstrack of changes to the matched set of elements When one of the DOM traversal methods iscalled the new set of elements is pushed onto the stack If the previous set of elements isdesired as well andSelf() can help
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
The result of the following code is a red background behind items 3 4 and 5
$( l i third-item)nextAll()andSelf() css(background-color red)
First the init ial selector locates item 3 init ializing the stack with the set containing just this itemThe call to nextAll() then pushes the set of items 4 and 5 onto the stack Finally the andSelf()invocat ion merges these two sets together creat ing a jQuery object that points to all three
items in document order [ltlithird-itemgtltligtltligt ]
Example 1 Find all divs and all the paragraphs inside of them and give them both class namesNot ice the div doesnt have the yellow background color since it didnt use andSelf()
Javascript
$(div)find(p)andSelf()addClass(border) $(div)find(p)addClass(background)
CSS
p div margin5px padding5px border border 2px solid red background backgroundyellow
HTML
ltdivgt ltpgtFirst Paragraphltpgt ltpgtSecond Paragraphltpgt ltdivgt
siblings
Get the siblings of each element in the set of matched elements opt ionally f iltered by aselector
Added in version 10
siblings(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the siblings() method allows usto search through the siblings of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
If we begin at the third item we can f ind its siblings
$( l i third-item)siblings()css(background-color red)
The result of this call is a red background behind items 1 2 4 and 5 Since we do not supply aselector expression all of the siblings are part of the object If we had supplied one only thematching items among these four would be included
The original element is not included among the siblings which is important to remember whenwe wish to f ind all elements at a part icular level of the DOM tree
Example 1 Find the unique siblings of all yellow li elements in the 3 lists (including other yellow lielements if appropriate)
Javascript
var len = $(hil ite)siblings() css(color red) length $(b)text(len)
CSS
ul floatleft margin5px font-size16px font-weightbold p colorblue margin10px 20px font-size16px padding5px font-weightbolder hi l ite backgroundyellow
HTML
ltulgt ltligtOneltligt
ltligtTwoltligt ltli class=hil itegtThreeltligt ltligtFourltligt ltulgt
ltulgt ltligtFiveltligt ltligtSixltligt ltligtSevenltligt
ltulgt ltulgt ltligtEightltligt ltli class=hil itegtNineltligt
ltligtTenltligt ltli class=hil itegtElevenltligt ltulgt ltpgtUnique siblings ltbgtltbgtltpgt
Example 2 Find all siblings with a class selected of each div
Javascript
$(p)siblings(selected)css(background yellow)
HTML
ltdivgtltspangtHelloltspangtltdivgt
ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt
prevAll
Get all preceding siblings of each element in the set of matched elements opt ionally f iltered bya selector
Added in version 12
prevAll(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the prevAll() method searchesthrough the predecessors of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements the elements are returned in order beginning with theclosest sibling
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
If we begin at the third item we can f ind the elements which come before it
$( l i third-item)prevAll()css(background-color red)
The result of this call is a red background behind items 1 and 2 Since we do not supply aselector expression these preceding elements are unequivocally included as part of the object If we had supplied one the elements would be tested for a match before they were included
Example 1 Locate all the divs preceding the last div and give them a class
Javascript
$(divlast)prevAll()addClass(before)
CSS
div width70px height70px backgroundabc border2px solid black margin10px floatleft divbefore border-color red
HTML
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
prev
Get the immediately preceding sibling of each element in the set of matched elementsopt ionally f iltered by a selector
Added in version 10
prev(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the prev() method allows us tosearch through the predecessors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
If we begin at the third item we can f ind the element which comes just before it
$( l i third-item)prev()css(background-color red)
The result of this call is a red background behind item 2 Since we do not supply a selectorexpression this preceding element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included
Example 1 Find the very previous sibling of each div
Javascript
var $curr = $(start) $currcss(background f99) $(button)cl ick(function () $curr = $currprev() $(div)css(background ) $currcss(background f99) )
CSS
div width40px height40px margin10px floatleft border2px blue solid padding2px span font-size14px p clearleft margin10px
HTML
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltspangthas childltspangtltdivgt
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdiv id=startgtltdivgt
ltdivgtltdivgt ltpgtltbuttongtGo to Prevltbuttongtltpgt
Example 2 For each paragraph f ind the very previous sibling that has a class selected
Javascript
$(p)prev(selected)css(background yellow)
HTML
ltdivgtltspangtHelloltspangtltdivgt
ltp class=selectedgtHello Againltpgt ltpgtAnd Againltpgt
parents
Get the ancestors of each element in the current set of matched elements opt ionally f iltered
by a selector
Added in version 10
parents(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the parents() method allows usto search through the ancestors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements ordered from immediate parent on up the elementsare returned in order f rom the closest parent to the outer ones The parents() and parent()methods are similar except that the lat ter only t ravels a single level up the DOM tree
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a basic nested list on it
ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
If we begin at item A we can f ind its ancestors
$( l i item-a)parents()css(background-color red)
The result of this call is a red background for the level-2 list item II and the level-1 list (and onup the DOM tree all the way to the lthtmlgt element) Since we do not supply a selectorexpression all of the ancestors are part of the returned jQuery object If we had supplied one
only the matching items among these would be included
Example 1 Find all parent elements of each b
Javascript
var parentEls = $(b)parents() map(function () return thistagName ) get()join( )$(b)append(ltstronggt + parentEls + ltstronggt)
CSS
b span p html body padding 5em border 1px solid b colorblue strong colorred
HTML
ltdivgt ltpgt ltspangt ltbgtMy parents are ltbgt ltspangt
ltpgt ltdivgt
Example 2 Click to f ind all unique div parent elements of each span
Javascript
function showParents() $(div)css(border-color white) var len = $(spanselected) parents(div) css(border 2px red solid) length $(b)text(Unique div parents + len)$(span)cl ick(function () $(this)toggleClass(selected) showParents())
CSS
p div span margin2px padding1px div border2px white solid span cursorpointer font-size12px selected colorblue b colorred displayblock font-size14px
HTML
ltpgt ltdivgt ltdivgtltspangtHelloltspangtltdivgt ltspangtHello Againltspangt
ltdivgt ltdivgt ltspangtAnd Hello Againltspangt ltdivgt ltpgt
ltbgtClick Hellos to toggle their parentsltbgt
parent
Get the parent of each element in the current set of matched elements opt ionally f iltered by aselector
Added in version 10
parent(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the parent() method allows usto search through the parents of these elements in the DOM tree and construct a new jQueryobject f rom the matching elements The parents() and parent() methods are similar exceptthat the lat ter only t ravels a single level up the DOM tree
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a basic nested list on it
ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
If we begin at item A we can f ind its parents
$( l i item-a)parent()css(background-color red)
The result of this call is a red background for the level-2 list Since we do not supply a selectorexpression the parent element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included
Example 1 Shows the parent of each element as (parent gt child) Check the View Source tosee the raw html
Javascript
$( documentbody)each(function () var parentTag = $(this)parent()get(0)tagName $(this)prepend(documentcreateTextNode(parentTag + gt )) )
CSS
divp margin10px
HTML
ltdivgtdiv ltspangtspan ltspangt ltbgtb ltbgt
ltdivgt ltpgtp ltspangtspan ltemgtem ltemgt ltspangt ltpgt
ltdivgtdiv ltstronggtstrong ltspangtspan ltspangt ltemgtem ltbgtb ltbgt ltemgt
ltstronggt ltbgtb ltbgt ltdivgt
Example 2 Find the parent element of each paragraph with a class selected
Javascript
$(p)parent(selected)css(background yellow)
HTML
ltdivgtltpgtHelloltpgtltdivgt
ltdiv class=selectedgtltpgtHello Againltpgtltdivgt
offsetParent
Get the closest ancestor element that is posit ioned
Added in version 126
offsetParent()jQuery
Given a jQuery object that represents a set of DOM elements the of fsetParent() methodallows us to search through the ancestors of these elements in the DOM tree and construct anew jQuery object wrapped around the closest posit ioned ancestor An element is said to beposit ioned if it has a CSS posit ion at t ribute of relat ive absolute or f ixed This informat ion isuseful for calculat ing of fsets for performing animat ions and placing objects on the page
Consider a page with a basic nested list on it with a posit ioned element
ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
If we begin at item A we can f ind its posit ioned ancestor
$( l i item-a)offsetParent()css(background-color red)
This will change the color of list item II which is posit ioned
Example 1 Find the of fsetParent of item A
Javascript
$( l i item-a)offsetParent()css(background-color red)
HTML
ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-ii style=position relativegtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igt ltulgt
nextAll
Get all following siblings of each element in the set of matched elements opt ionally f iltered bya selector
Added in version 12
nextAll(selector)jQuery
selectorString (opt ional) A string containing a selector expression to match elementsagainst
Given a jQuery object that represents a set of DOM elements the nextAll() method allows usto search through the successors of these elements in the DOM tree and construct a newjQuery object f rom the matching elements
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
If we begin at the third item we can f ind the elements which come after it
$( l i third-item)nextAll()css(background-color red)
The result of this call is a red background behind items 4 and 5 Since we do not supply aselector expression these following elements are unequivocally included as part of the object If we had supplied one the elements would be tested for a match before they were included
Example 1 Locate all the divs af ter the f irst and give them a class
Javascript
$(divfirst)nextAll()addClass(after)
CSS
div width 80px height 80px background abc border 2px solid black margin 10px float left divafter border-color red
HTML
ltdivgtfirstltdivgt ltdivgtsiblingltdivgtchildltdivgtltdivgt ltdivgtsiblingltdivgt
ltdivgtsiblingltdivgt
Example 2 Locate all the paragraphs af ter the second child in the body and give them a class
Javascript
$(nth-child(1))nextAll(p)addClass(after)
CSS
div p width 60px height 60px background abc border 2px solid black margin 10px float left after border-color red
HTML
ltpgtpltpgt
ltdivgtdivltdivgt ltpgtpltpgt ltpgtpltpgt ltdivgtdivltdivgt
ltpgtpltpgt ltdivgtdivltdivgt
next
Get the immediately following sibling of each element in the set of matched elements If aselector is provided it retrieves the next sibling only if it matches that selector
Added in version 10
next(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the next() method allows us tosearch through the immediately following sibling of these elements in the DOM tree andconstruct a new jQuery object f rom the matching elements
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the immediately following sibling matches the selector it remains in the newlyconstructed jQuery object otherwise it is excluded
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli class=third-itemgtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
If we begin at the third item we can f ind the element which comes just af ter it
$( l i third-item)next()css(background-color red)
The result of this call is a red background behind item 4 Since we do not supply a selector
expression this following element is unequivocally included as part of the object If we hadsupplied one the element would be tested for a match before it was included
Example 1 Find the very next sibling of each disabled button and change its text this button isdisabled
Javascript
$(button[disabled])next()text(this button is disabled)
CSS
span colorblue font-weightbold button width100px
HTML
ltdivgtltbutton disabled=disabledgtFirstltbuttongt - ltspangtltspangtltdivgt ltdivgtltbuttongtSecondltbuttongt - ltspangtltspangtltdivgt
ltdivgtltbutton disabled=disabledgtThirdltbuttongt - ltspangtltspangtltdivgt
Example 2 Find the very next sibling of each paragraph Keep only the ones with a classselected
Javascript
$(p)next(selected)css(background yellow)
HTML
ltpgtHelloltpgt
ltp class=selectedgtHello Againltpgt ltdivgtltspangtAnd Againltspangtltdivgt
find
Get the descendants of each element in the current set of matched elements f iltered by aselector jQuery object or element
Added in version 16
f ind(element)jQuery
elementElement An element to match elements against
Given a jQuery object that represents a set of DOM elements the f ind() method allows us tosearch through the descendants of these elements in the DOM tree and construct a newjQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree
The f irst signature for the f ind()method accepts a selector expression of the same type thatwe can pass to the $() funct ion The elements will be f iltered by test ing whether they match thisselector
Consider a page with a basic nested list on it
ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
If we begin at item II we can f ind list items within it
$( l i item-ii )find( l i )css(background-color red)
The result of this call is a red background on items A B 1 2 3 and C Even though item IImatches the selector expression it is not included in the results only descendants areconsidered candidates for the match
Unlike in the rest of the tree traversal methods the selector expression is requiredin a call to find() If we need to retrieve all of the descendant elements we canpass in the universal selector to accomplish this
Selector context is implemented with the f ind() method therefore $(liitem-ii)f ind(li) isequivalent to $(li liitem-ii)
As of jQuery 16 we can also f ilter the select ion with a given jQuery collect ion or element Withthe same nested list as above if we start with
var $allListElements = $( l i )
And then pass this jQuery object to f ind
$( l i item-ii )find( $allListElements )
This will return a jQuery collect ion which contains only the list elements that are descendantsof item II
Similarly an element may also be passed to f ind
var item1 = $( l i item-1)[0]$( l i item-ii )find( item1 )css(background-color red)
The result of this call would be a red background on item 1
Example 1 Starts with all paragraphs and searches for descendant span elements same as$(p span)
Javascript
$(p)find(span)css(color red)
HTML
ltpgtltspangtHelloltspangt how are youltpgtltpgtMe Im ltspangtgoodltspangtltpgt
Example 2 A select ion using a jQuery collect ion of all span tags Only spans within p tags arechanged to red while others are lef t blue
CSS
span color blue
Javascript
var $spans = $(span) $(p)find( $spans )css(color red)
HTML
ltpgtltspangtHelloltspangt how are youltpgt ltpgtMe Im ltspangtgoodltspangtltpgt ltdivgtDid you ltspangteatltspangt yetltdivgt
Example 3 Add spans around each word then add a hover and italicize words with the let ter t
Javascript
var newText = $(p)text()split( )join(ltspangt ltspangt) newText = ltspangt + newText + ltspangt
$(p)html( newText ) find(span) hover(function() $(this)addClass(hil ite) function() $(this)removeClass(hil ite) ) end() find(contains(t)) css(font-style ital ic font-weightbolder)
CSS
p font-size20px width200px cursordefault colorblue font-weightbold margin0 10px hi l ite backgroundyellow
HTML
ltpgt When the day is short find that which matters to you or stop believing ltpgt
contents
Get the children of each element in the set of matched elements including text and commentnodes
Added in version 12
contents()jQuery
Given a jQuery object that represents a set of DOM elements the contents() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The contents() and children() methods aresimilar except that the former includes text nodes as well as HTML elements in the result ingjQuery object
The contents() method can also be used to get the content document of an if rame if theif rame is on the same domain as the main page
Consider a simple ltdivgt with a number of text nodes each of which is separated by two linebreak elements (ltbr gt)
ltdiv class=containergt Lorem ipsum dolor sit amet consectetur adipisicing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua ltbr gtltbr gt Ut enim ad minim veniam quis nostrud exercitation ullamco laboris nisi ut al iquip ex ea commodo consequat ltbr gt ltbr gt Duis aute irure dolor in reprehenderit in voluptate velit esse ci l lum dolore eu fugiat nulla pariaturltdivgt
We can employ the contents() method to help convert this blob of text into three well-formedparagraphs
$(container)contents()fi lter(function() return thisnodeType == 3) wrap(ltpgtltpgt)end()fi lter(br) remove()
This code f irst retrieves the contents of ltdiv class=containergt and then f ilters it for textnodes which are wrapped in paragraph tags This is accomplished by test ing the nodeTypeproperty of the element This DOM property holds a numeric code indicat ing the nodes typetext nodes use the code 3 The contents are again f iltered this t ime for ltbr gt elements andthese elements are removed
Example 1 Find all the text nodes inside a paragraph and wrap them with a bold tag
Javascript
$(p)contents()fi lter(function() return thisnodeType = 1 )wrap(ltbgt)
HTML
ltpgtHello lta href=httpejohnorggtJohnltagt how are you doingltpgt
Example 2 Change the background colour of links inside of an if rame
Javascript
$(frameDemo)contents()find(a)css(background-colorBADA55)
HTML
ltiframe src=httpapijquerycom width=80 height=600 id=frameDemogtltiframegt
closest
Get the f irst ancestor element that matches the selector beginning at the current element andprogressing up through the DOM tree
Added in version 16
closest(element)jQuery
elementElement An element to match elements against
Given a jQuery object that represents a set of DOM elements the closest() method allows usto search through these elements and their ancestors in the DOM tree and construct a newjQuery object f rom the matching elements The parents() and closest() methods are similar inthat they both t raverse up the DOM tree The dif ferences between the two though subt le aresignif icant
closest() parents()
Begins with thecurrent element
Begins with the parent element
Travels up the DOMtree unt il it f inds amatch for the suppliedselector
Travels up the DOM tree to the document s root elementadding each ancestor element to a temporary collect ion it thenf ilters that collect ion based on a selector if one is supplied
The returned jQueryobject contains zeroor one element
The returned jQuery object contains zero one or mult ipleelements
ltul id=one class=level-1gt ltli class=item-igtIltl igt ltli id=ii class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
Suppose we perform a search for ltulgt elements start ing at item A
$( l i item-a)closest(ul ) css(background-color red)
This will change the color of the level-2 ltulgt since it is the f irst encountered when traveling upthe DOM tree
Suppose we search for an ltligt element instead
$( l i item-a)closest( l i ) css(background-color red)
This will change the color of list item A The closest() method begins its search with theelement itself before progressing up the DOM tree and stops when item A matches theselector
We can pass in a DOM element as the context within which to search for the closest element
var l istItemII = documentgetElementById( i i )$( l i item-a)closest(ul l istItemII) css(background-color red)$( l i item-a)closest(one l istItemII) css(background-color green)
This will change the color of the level-2 ltulgt because it is both the f irst ltulgt ancestor of listitem A and a descendant of list item II It will not change the color of the level-1 ltulgt howeverbecause it is not a descendant of list item II
Example 1 Show how event delegat ion can be done with closest The closest list elementtoggles a yellow background when it or its descendent is clicked
Javascript
$( document )bind(click function( e ) $( etarget )closest(l i)toggleClass(hil ight) )
CSS
l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow
HTML
ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt
Example 2 Pass a jQuery object to closest The closest list element toggles a yellowbackground when it or its descendent is clicked
Javascript
var $listElements = $(l i)css(color blue) $( document )bind(click function( e ) $( etarget )closest( $listElements )toggleClass(hil ight) )
CSS
l i margin 3px padding 3px background EEEEEE l i hi l ight background yellow
HTML
ltulgt ltligtltbgtClick meltbgtltligt ltligtYou can also ltbgtClick meltbgtltligt ltulgt
closest
Gets an array of all the elements and selectors matched against the current element upthrough the DOM tree
Added in version 14
closest(selectors context)Array
selectorsArray An array or string containing a selector expression to match elementsagainst (can also be a jQuery object)
context Element (opt ional) A DOM element within which a matching element may befound If no context is passed in then the context of the jQuery setwill be used instead
This method is primarily meant to be used internally or by plugin authors
Example 1 Show how event delegat ion can be done with closest
Javascript
var close = $(l i first)closest([ul body]) $each(close function(i) $(l i)eq(i)html( thisselector + + thiselemnodeName ) )
CSS
HTML
ltulgtltligtltligtltligtltligtltulgt
children
Get the children of each element in the set of matched elements opt ionally f iltered by aselector
Added in version 10
children(selector)jQuery
selectorSelector (opt ional) A string containing a selector expression to matchelements against
Given a jQuery object that represents a set of DOM elements the children() method allows usto search through the immediate children of these elements in the DOM tree and construct anew jQuery object f rom the matching elements The f ind() and children() methods are similarexcept that the lat ter only t ravels a single level down the DOM tree Note also that like mostjQuery methods children() does not return text nodes to get all children including text andcomment nodes use contents()
The method opt ionally accepts a selector expression of the same type that we can pass to the$() funct ion If the selector is supplied the elements will be f iltered by test ing whether theymatch it
Consider a page with a basic nested list on it
ltul class=level-1gt ltli class=item-igtIltl igt ltli class=item-iigtII ltul class=level-2gt ltli class=item-agtAltligt ltli class=item-bgtB ltul class=level-3gt ltli class=item-1gt1ltligt ltli class=item-2gt2ltligt ltli class=item-3gt3ltligt ltulgt ltl igt ltli class=item-cgtCltligt ltulgt ltl igt ltli class=item-ii igtIIIltl igtltulgt
If we begin at the level-2 list we can f ind its children
$(ullevel-2)children()css(background-color red)
The result of this call is a red background behind items A B and C Since we do not supply aselector expression all of the children are part of the returned jQuery object If we had suppliedone only the matching items among these three would be included
Example 1 Find all children of the clicked element
Javascript
$(container)cl ick(function (e) $()removeClass(hil ite) var $kids = $(etarget)children() var len = $kidsaddClass(hil ite)length
$(results spanfirst)text(len) $(results spanlast)text(etargettagName)
epreventDefault() return false )
CSS
body font-size16px font-weightbolder div width130px height82px margin10px floatleft border1px solid blue padding4px container widthauto height105px margin0 floatnone bordernone hi l ite border-colorred results displayblock colorred p margin10px border1px solid transparent span colorblue border1px solid transparent input width100px em border1px solid transparent a border1px solid transparent b border1px solid transparent button border1px solid transparent
HTML
ltdiv id=containergt
ltdivgt ltpgtThis ltspangtis the ltemgtwayltemgt weltspangt write ltemgttheltemgt demoltpgt
ltdivgt ltdivgt lta href=gtltbgtwltbgtritltbgteltbgtltagt the ltspangtdemoltspangt ltbuttongtwrite theltbuttongt demo ltdivgt
ltdivgt This ltspangtthe way we ltemgtwriteltemgt the ltemgtdemoltemgt soltspangt
ltinput type=text value=early gt in ltdivgt ltpgt ltspangttltspangthe ltspangtmltspangtorning ltspan id=resultsgtFound ltspangt0ltspangt children in ltspangtTAGltspangtltspangt
ltpgt ltdivgt
Example 2 Find all children of each div
Javascript
$(div)children()css(border-bottom 3px double red)
CSS
body font-size16px font-weightbolder span colorblue p margin5px 0
HTML
ltpgtHello (this is a paragraph)ltpgt
ltdivgtltspangtHello Again (this span is a child of the a div)ltspangtltdivgt ltpgtAnd ltspangtAgainltspangt (in another paragraph)ltpgt
ltdivgtAnd One Last ltspangtTimeltspangt (most text directly in a div)ltdivgt
Example 3 Find all children with a class selected of each div
Javascript
$(div)children(selected)css(color blue)
CSS
body font-size16px font-weightbolder p margin5px 0
HTML
ltdivgt ltspangtHelloltspangt ltp class=selectedgtHello Againltpgt ltdiv class=selectedgtAnd Againltdivgt
ltpgtAnd One Last Timeltpgt ltdivgt
add
Add elements to the set of matched elements
Added in version 14
add(selector context)jQuery
selectorSelector A string represent ing a selector expression to f ind addit ionalelements to add to the set of matched elements
context Element The point in the document at which the selector should beginmatching similar to the context argument of the $(selector context)method
Given a jQuery object that represents a set of DOM elements the add() method constructs anew jQuery object f rom the union of those elements and the ones passed into the methodThe argument to add() can be pret ty much anything that $() accepts including a jQueryselector expression references to DOM elements or an HTML snippet
The updated set of elements can be used in a following (chained) method or assigned to avariable for later use For example
$(p)add(div)addClass(widget)var pdiv = $(p)add(div)
The following will not save the added elements because the add() method creates a new setand leaves the original set in pdiv unchanged
var pdiv = $(p)pdivadd(div) WRONG pdiv wil l not change
Consider a page with a simple list and a paragraph following it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligtltulgtltpgta paragraphltpgt
We can select the list items and then the paragraph by using either a selector or a reference tothe DOM element itself as the add() methods argument
$( l i )add(p)css(background-color red)
Or
$( l i )add(documentgetElementsByTagName(p)[0]) css(background-color red)
The result of this call is a red background behind all four elements Using an HTML snippet asthe add() methods argument (as in the third version) we can create addit ional elements on thef ly and add those elements to the matched set of elements Let s say for example that wewant to alter the background of the list items along with a newly created paragraph
$( l i )add(ltp id=newgtnew paragraphltpgt) css(background-color red)
Although the new paragraph has been created and its background color changed it st ill doesnot appear on the page To place it on the page we could add one of the insert ion methods tothe chain
As of jQuery 14 the results f rom add() will always be returned in document order (rather than asimple concatenat ion)
Note To reverse the add() you can use not( elements | selector ) to remove elements f rom thejQuery results or end() to return to the select ion before you added
Example 1 Finds all divs and makes a border Then adds all paragraphs to the jQuery object toset their backgrounds yellow
Javascript
$(div)css(border 2px solid red) add(p) css(background yellow)
CSS
div width60px height60px margin10px floatleft p clearleft font-weightbold font-size16px colorblue margin0 10px padding2px
HTML
ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
ltpgtAdded this (notice no border)ltpgt
Example 2 Adds more elements matched by the given expression to the set of matchedelements
Javascript
$(p)add(span)css(background yellow)
HTML
ltpgtHelloltpgtltspangtHello Againltspangt
Example 3 Adds more elements created on the f ly to the set of matched elements
Javascript
$(p)clone()add(ltspangtAgainltspangt)appendTo(documentbody)
HTML
ltpgtHelloltpgt
Example 4 Adds one or more Elements to the set of matched elements
Javascript
$(p)add(documentgetElementById(a))css(background yellow)
HTML
ltpgtHelloltpgtltspan id=agtHello Againltspangt
Example 5 Demonstrates how to add (or push) elements to an exist ing collect ion
Javascript
var collection = $(p) capture the new collectioncollection = collectionadd(documentgetElementById(a))collectioncss(background yellow)
HTML
ltpgtHelloltpgtltspan id=agtHello Againltspangt
not
Remove elements f rom the set of matched elements
Added in version 14
not(funct ion(index))jQuery
funct ion(index)Funct ion A funct ion used as a test for each element in the set this isthe current DOM element
Given a jQuery object that represents a set of DOM elements the not() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element the elements that dont match the selector will be included in the result
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
We can apply this method to the set of list items
$( l i )not(even)css(background-color red)
The result of this call is a red background for items 2 and 4 as they do not match the selector(recall that even and odd use 0-based indexing)
Removing Specific Elements
The second version of the not() method allows us to remove elements f rom the matched setassuming we have found those elements previously by some other means For examplesuppose our list had an id applied to one of its items
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltli id=notligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
We can fetch the third list item using the nat ive JavaScript getElementById() funct ion thenremove it f rom a jQuery object
$( l i )not(documentgetElementById(notl i )) css(background-color red)
This statement changes the color of items 1 2 4 and 5 We could have accomplished thesame thing with a simpler jQuery expression but this technique can be useful when forexample other libraries provide references to plain DOM nodes
As of jQuery 14 the not() method can take a funct ion as its argument in the same way thatf ilter() does Elements for which the funct ion returns t rue are excluded from the f iltered set allother elements are included
Example 1 Adds a border to divs that are not green or blue
Javascript
$(div)not(green blueone) css(border-color red)
CSS
div width50px height50px margin10px floatleft backgroundyellow border2px solid white green background8f8 gray backgroundccc blueone background99f
HTML
ltdivgtltdivgt ltdiv id=blueonegtltdivgt ltdivgtltdivgt ltdiv class=greengtltdivgt
ltdiv class=greengtltdivgt ltdiv class=graygtltdivgt ltdivgtltdivgt
Example 2 Removes the element with the ID selected f rom the set of all paragraphs
Javascript
$(p)not( $(selected)[0] )
Example 3 Removes the element with the ID selected f rom the set of all paragraphs
Javascript
$(p)not(selected)
Example 4 Removes all elements that match div pselected f rom the total set of allparagraphs
Javascript
$(p)not($(div pselected))
map
Pass each element in the current matched set through a funct ion producing a new jQueryobject containing the return values
Added in version 12
map(callback(index domElement))jQuery
callback(indexdomElement)Funct ion
A funct ion object that will be invoked for each element inthe current set
As the return value is a jQuery-wrapped array it s very common to get() the returned object towork with a basic array
The map() method is part icularly useful for gett ing or set t ing the value of a collect ion ofelements Consider a form with a set of checkboxes in it
ltform method=post action=gt ltfieldsetgt ltdivgt ltlabel for=twogt2ltlabelgt ltinput type=checkbox value=2 id=two name=number[]gt ltdivgt ltdivgt ltlabel for=fourgt4ltlabelgt ltinput type=checkbox value=4 id=four name=number[]gt ltdivgt ltdivgt ltlabel for=sixgt6ltlabelgt ltinput type=checkbox value=6 id=six name=number[]gt ltdivgt ltdivgt ltlabel for=eightgt8ltlabelgt ltinput type=checkbox value=8 id=eight name=number[]gt ltdivgt ltfieldsetgtltformgt
We can get a comma-separated list of checkbox IDs
$(checkbox)map(function() return thisid)get()join( )
The result of this call is the string twofoursixeight
Within the callback funct ion this refers to the current DOM element for each iterat ion Thefunct ion can return an individual data item or an array of data items to be inserted into theresult ing set If an array is returned the elements inside the array are inserted into the set If thefunct ion returns null or undef ined no element will be inserted
Example 1 Build a list of all the values within a form
Javascript
$(p)append( $(input)map(function() return $(this)val() )get()join( ) )
CSS
p colorred
HTML
ltpgtltbgtValues ltbgtltpgt ltformgt ltinput type=text name=name value=Johngt
ltinput type=text name=password value=passwordgt ltinput type=text name=url value=httpejohnorggt
ltformgt
Example 2 A contrived example to show some funct ionality
Javascript
var mappedItems = $(l i)map(function (index) var replacement = $(ltligt)text($(this)text())get(0) i f (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$(ltligt)get(0)] $(replacement[0])append(ltbgt - Altbgt) $(replacement[1])append(Extra ltbgt - Bltbgt)
replacement wil l be a dom element null or an array of dom elements return replacement)$(results)append(mappedItems)
CSS
body font-size16px ul floatleft margin0 30px colorblue results colorred
HTML
ltulgt ltligtFirstltl igt ltligtSecondltligt ltligtThirdltligt
ltligtFourthltligt ltligtFifthltligt ltulgt ltul id=resultsgt
ltulgt
Example 3 Equalize the heights of the divs
Javascript
$fnequalizeHeights = function() var maxHeight = thismap(function(ie) return $(e)height() )get() return thisheight( Mathmaxapply(this maxHeight) )
$( input)cl ick(function() $(div)equalizeHeights())
CSS
div width 40px floatleft input clearleft
HTML
ltinput type=button value=equalize div heightsgt
ltdiv style=backgroundred height 40px gtltdivgtltdiv style=backgroundgreen height 70pxgtltdivgtltdiv style=backgroundblue height 50px gtltdivgt
is
Check the current matched set of elements against a selector element or jQuery object andreturn t rue if at least one of these elements matches the given arguments
Added in version 16
is(element)Boolean
elementElement An element to match the current set of elements against
Unlike other f iltering methods is() does not create a new jQuery object Instead it allows youto test the contents of a jQuery object without modif icat ion This is of ten useful insidecallbacks such as event handlers
Suppose you have a list with two of its items containing a child element
ltulgt ltligtlist ltstronggtitem 1ltstronggtltligt ltligtltspangtlist item 2ltspangtltligt ltligtlist item 3ltligtltulgt
You can at tach a click handler to the ltulgt element and then limit the code to be triggered onlywhen a list item itself not one of its children is clicked
$(ul)cl ick(function(event) var $target = $(eventtarget) i f ( $targetis( l i) ) $targetcss(background-color red) )
Now when the user clicks on the word list in the f irst item or anywhere in the third item theclicked list item will be given a red background However when the user clicks on item 1 in thef irst item or anywhere in the second item nothing will occur because in those cases the targetof the event would be ltstronggt or ltspangt respect ively
Be aware that for selector strings with posit ional selectors such as f irst gt() or even theposit ional f iltering is done against the jQuery object passed to is() not against the containingdocument So for the HTML shown above an expression such as $(lif irst)is(lilast) returnstrue but $(lif irst-child)is(lilast-child) returns false
Using a Function
The second form of this method evaluates expressions related to elements based on afunct ion rather than a selector For each element if the funct ion returns t rue is() returns t rueas well For example given a somewhat more involved HTML snippet
ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligtltulgt
You can at tach a click handler to every ltligt that evaluates the number of ltstronggt elementswithin the clicked ltligt at that t ime like so
$(l i)cl ick(function() var $li = $(this) isWithTwo = $liis(function() return $(strong this)length === 2 ) i f ( isWithTwo ) $l i css(background-color green) else $l i css(background-color red) )
Example 1 Shows a few ways is() can be used inside an event handler
Javascript
$(div)one(cl ick function () i f ($(this)is(first-child)) $(p)text(Its the first div) else if ($(this)is(bluered)) $(p)text(Its a blue or red div) else if ($(this)is(contains(Peter))) $(p)text(Its Peter) else $(p)html(Its nothing ltemgtspecialltemgt) $(p)hide()sl ideDown(slow) $(this)css(border-style inset cursordefault) )
CSS
div width60px height60px margin5px floatleft border4px outset backgroundgreen text-aligncenter font-weightbolder cursorpointer blue backgroundblue red backgroundred span colorwhite font-size16px p colorred font-weightbolder backgroundyellow margin3px clearleft displaynone
HTML
ltdivgtltdivgtltdiv class=bluegtltdivgtltdivgtltdivgtltdiv class=redgtltdivgt
ltdivgtltbrgtltspangtPeterltspangtltdivgtltdiv class=bluegtltdivgtltpgtampnbspltpgt
Example 2 Returns t rue because the parent of the input is a form element
Javascript
var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)
CSS
div colorred
HTML
ltformgtltinput type=checkbox gtltformgtltdivgtltdivgt
Example 3 Returns false because the parent of the input is a p element
Javascript
var isFormParent = $(input[type=checkbox])parent()is(form) $(div)text(isFormParent = + isFormParent)
CSS
div colorred
HTML
ltformgtltpgtltinput type=checkbox gtltpgtltformgt ltdivgtltdivgt
Example 4 Checks against an exist ing collect ion of alternat ing list elements Blue alternat inglist elements slide up while others turn red
Javascript
var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() var $li = $(this) i f ( $l i is( $alt ) ) $l i sl ideUp() else $l i css(background red) )
CSS
l i cursorpointer
HTML
ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt
Example 5 An alternate way to achieve the above example using an element rather than ajQuery object Checks against an exist ing collect ion of alternat ing list elements Bluealternat ing list elements slide up while others turn red
Javascript
var $alt = $(browsers l i nth-child(2n))css(background 00FFFF) $( l i )cl ick(function() i f ( $altis( this ) ) $(this)sl ideUp() else $(this)css(background red) )
CSS
l i cursorpointer
HTML
ltul id=browsersgt ltligtChromeltligt ltligtSafariltl igt ltligtFirefoxltligt ltligtOperaltligtltulgt
eq
Reduce the set of matched elements to the one at the specif ied index
Added in version 14
eq(-index)jQuery
-indexInteger
An integer indicat ing the posit ion of the element count ing backwardsfrom the last element in the set
Given a jQuery object that represents a set of DOM elements the eq() method constructs anew jQuery object f rom one element within that set The supplied index ident if ies the posit ionof this element in the set
Consider a page with a simple list on it
ltulgt ltligtlist item 1ltligt ltligtlist item 2ltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltulgt
We can apply this method to the set of list items
$( l i )eq(2)css(background-color red)
The result of this call is a red background for item 3 Note that the supplied index is zero-basedand refers to the posit ion of the element within the jQuery object not within the DOM tree
Providing a negat ive number indicates a posit ion start ing f rom the end of the set rather thanthe beginning For example
$( l i )eq(-2)css(background-color red)
This t ime list item 4 is turned red since it is two from the end of the set
If an element cannot be found at the specif ied zero-based index the method constructs a newjQuery object with an empty set and a length property of 0
$( l i )eq(5)css(background-color red)
Here none of the list items is turned red since eq(5) indicates the sixth of f ive list items
Example 1 Turn the div with index 2 blue by adding an appropriate class
Javascript
$(body)find(div)eq(2)addClass(blue)
CSS
div width60px height60px margin10px floatleft border2px solid blue blue backgroundblue
HTML
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
filter
Reduce the set of matched elements to those that match the selector or pass the funct ionstest
Added in version 14
f ilter(jQuery object)jQuery
jQueryobject Object
An exist ing jQuery object to match the current set of elementsagainst
Given a jQuery object that represents a set of DOM elements the f ilter() method constructs anew jQuery object f rom a subset of the matching elements The supplied selector is tested
new jQuery object f rom a subset of the matching elements The supplied selector is testedagainst each element all elements matching the selector will be included in the result
Consider a page with a simple list on it
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
We can apply this method to the set of list items
$( l i )fi lter( even)css(background-color red)
The result of this call is a red background for items 1 3 and 5 as they match the selector(recall that even and odd use 0-based indexing)
Using a Filter Function
The second form of this method allows us to f ilter elements against a funct ion rather than aselector For each element if the funct ion returns t rue (or a t ruthy value) the element will beincluded in the f iltered set otherwise it will be excluded Suppose we have a somewhat moreinvolved HTML snippet
ltulgt ltligtltstronggtlistltstronggt item 1 - one strong tagltligt ltligtltstronggtlistltstronggt item ltstronggt2ltstronggt - two ltspangtstrong tagsltspangtltligt ltligtlist item 3ltligt ltligtlist item 4ltligt ltligtlist item 5ltligt ltligtlist item 6ltligtltulgt
We can select the list items then f ilter them based on their contents
$( l i )fi lter(function(index) return $(strong this)length == 1)css(background-color red)
This code will alter the f irst list item only as it contains exact ly one ltstronggt tag Within the
f ilter funct ion this refers to each DOM element in turn The parameter passed to the funct iontells us the index of that DOM element within the set matched by the jQuery object
We can also take advantage of the index passed through the funct ion which indicates the 0-based posit ion of the element within the unf iltered set of matched elements
$( l i )fi lter(function(index) return index 3 == 2)css(background-color red)
This alterat ion to the code will cause the third and sixth list items to be highlighted as it usesthe modulus operator () to select every item with an index value that when divided by 3 hasa remainder of 2
Example 1 Change the color of all divs then add a border to those with a middle class
Javascript
$(div)css(background c8ebcc) fi lter(middle) css(border-color red)
CSS
div width60px height60px margin5px floatleft border2px white solid
HTML
ltdivgtltdivgt
ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt ltdiv class=middlegtltdivgt
ltdivgtltdivgt
Example 2 Change the color of all divs then add a border to the second one (index == 1) andthe div with an id of fourth
Javascript
$(div)css(background b4b0da) fi lter(function (index) return index == 1 || $(this)attr( id) == fourth ) css(border 3px double red)
CSS
div width60px height60px margin5px floatleft border3px white solid
HTML
ltdiv id=firstgtltdivgt ltdiv id=secondgtltdivgt ltdiv id=thirdgtltdivgt
ltdiv id=fourthgtltdivgt ltdiv id=fifthgtltdivgt ltdiv id=sixthgtltdivgt
Example 3 Select all divs and f ilter the select ion with a DOM element keeping only the one withan id of unique
Javascript
$(div)fi lter( documentgetElementById(unique) )
Example 4 Select all divs and f ilter the select ion with a jQuery object keeping only the one withan id of unique
Javascript
$(div)fi lter( $(unique) )
Attributes
removeProp
Remove a property for the set of matched elements
Added in version 16
removeProp(propertyName)jQuery
propertyNameString The name of the property to set
The removeProp() method removes propert ies set by the prop() method
With some built -in propert ies of a DOM element or window object browsers may generate anerror if an at tempt is made to remove the property jQuery f irst assigns the value undef ined tothe property and ignores any error the browser generates In general it is only necessary toremove custom propert ies that have been set on an object and not built -in (nat ive) propert ies
Note Do not use this method to remove nat ive propert ies such as checked disabled orselected This will remove the property completely and once removed cannot be added againto element Use prop() to set these propert ies to false instead
Example 1 Set a numeric property on a paragraph and then remove it
Javascript
var $para = $(p)$paraprop(luggageCode 1234)$paraappend(The secret luggage code is String($paraprop(luggageCode)) )$pararemoveProp(luggageCode)$paraappend(Now the secret luggage code is String($paraprop(luggageCode)) )
CSS
img padding10px div colorred font-size24px
HTML
ltpgtltpgt
prop
Get the value of a property for the f irst element in the set of matched elements
Added in version 16
prop(propertyName)String
propertyNameString The name of the property to get
The prop() method gets the property value for only the first element in the matched set Itreturns undef ined for the value of a property that has not been set or if the matched set hasno elements To get the value for each element individually use a looping construct such asjQuerys each() or map() method
The dif ference between attributes and properties can be important in specif ic situat ions BeforejQuery 16 the at t r() method sometimes took property values into account when retrievingsome attributes which could cause inconsistent behavior As of jQuery 16 the prop() methodprovides a way to explicit ly retrieve property values while at t r() retrieves at t ributes
For example selectedIndex tagName nodeName nodeType ownerDocumentdefaultChecked and defaultSelected should be retrieved and set with the prop() method Priorto jQuery 16 these propert ies were retrievable with the at t r() method but this was not withinthe scope of at t r These do not have corresponding at t ributes and are only propert ies
Concerning boolean at t ributes consider a DOM element def ined by the HTML markup ltinputtype=checkbox checked=checked gt and assume it is in a JavaScript variable named elem
elemchecked t rue (Boolean) Will change with checkbox state
$(elem)prop(checked) t rue (Boolean) Will change with checkbox state
elemgetAttribute(checked)checked (String) Init ial state of the checkbox doesnot change
$(elem)attr(checked)(16)checked (String) Init ial state of the checkbox doesnot change
$(elem)attr(checked)(161+) checked (String) Will change with checkbox state
$(elem)attr(checked)(pre-16)
t rue (Boolean) Changed with checkbox state
According to the W3C forms specif icat ion the checked at t ribute is a boolean attribute whichmeans the corresponding property is t rue if the at t ribute is present at allacirceurordquoeven if for examplethe at t ribute has no value or an empty string value The preferred cross-browser-compat ibleway to determine if a checkbox is checked is to check for a t ruthy value on the element sproperty using one of the following
if ( elemchecked )
if ( $(elem)prop(checked) )
if ( $(elem)is(checked) )
If using jQuery 16 the code if ( $(elem)at t r(checked) ) will retrieve the actual content attributewhich does not change as the checkbox is checked and unchecked It is meant only to storethe default or init ial value of the checked property To maintain backwards compatability theat t r() method in jQuery 161+ will retrieve and update the property for you so no code forboolean at t ributes is required to be changed to prop() Nevertheless the preferred way toretrieve a checked value is with one of the opt ions listed above To see how this works in thelatest jQuery checkuncheck the checkbox in the example below
Example 1 Display the checked property and at t ribute of a checkbox as it changes
Javascript
$(input)change(function() var $input = $(this) $(p)html(attr(checked) ltbgt + $inputattr(checked) + ltbgtltbrgt + prop(checked) ltbgt + $inputprop(checked) + ltbgtltbrgt + is( checked) ltbgt + $inputis( checked) ) + ltbgt)change()
CSS
p margin 20px 0 0 b color blue
HTML
ltinput id=check1 type=checkbox checked=checkedgtltlabel for=check1gtCheck meltlabelgtltpgtltpgt
prop
Set one or more propert ies for the set of matched elements
Added in version 16
prop(propertyName funct ion(index oldPropertyValue))jQuery
propertyNameString The name of the property to set
funct ion(indexoldPropertyValue)Funct ion
A funct ion returning the value to set Receives the indexposit ion of the element in the set and the old propertyvalue as arguments Within the funct ion the keyword thisrefers to the current element
The prop() method is a convenient way to set the value of propert iesacirceurordquoespecially whensett ing mult iple propert ies using values returned by a funct ion or set t ing values on mult ipleelements at once It should be used when sett ing selectedIndex tagName nodeNamenodeType ownerDocument defaultChecked or defaultSelected Since jQuery 16 thesepropert ies can no longer be set with the at t r() method They do not have correspondingattributes and are only propert ies
Propert ies generally af fect the dynamic state of a DOM element without changing theserialized HTML attribute Examples include the value property of input elements the disabledproperty of inputs and buttons or the checked property of a checkbox The prop() methodshould be used to set disabled and checked instead of the at t r() method The val() methodshould be used for gett ing and sett ing value
$(input)prop(disabled false)$(input)prop(checked true)$(input)val(someValue)
Important the removeProp() method should not be used to set these propert ies to false Oncea nat ive property is removed it cannot be added again See removeProp() for moreinformat ion
Computed property values
By using a funct ion to set propert ies you can compute the value based on other propert ies ofthe element For example to toggle all checkboxes based of f their individual values
$(input[type=checkbox])prop(checked function( i val ) return val)
Note If nothing is returned in the setter funct ion (ie funct ion(index prop)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met
Example 1 Disable all checkboxes on the page
Javascript
$(input[type=checkbox])prop( disabled true)
CSS
img padding10px div colorred font-size24px
HTML
ltinput type=checkbox checked=checked gt ltinput type=checkbox gt ltinput type=checkbox gt ltinput type=checkbox checked=checked gt
val
Get the current value of the f irst element in the set of matched elements
Added in version 10
val()String Number Array
The val() method is primarily used to get the values of form elements In the case of ltselectmult iple=mult iplegt elements the val() method returns an array containing each selectedopt ion
For selects and checkboxes you can also use the selected and checked selectors to get atvalues for example
$(selectfoo optionselected)val() get the value from a dropdown select$(selectfoo)val() get the value from a dropdown select even easier$( inputcheckboxchecked)val() get the value from a checked checkbox$( inputradio[name=bar]checked)val() get the value from a set of radio buttons
Example 1 Get the single value from a single select and an array of values from a mult ipleselect and display their values
Javascript
function displayVals() var singleValues = $(single)val() var multipleValues = $(multiple)val() || [] $(p)html(ltbgtSingleltbgt + singleValues + ltbgtMultipleltbgt + multipleValuesjoin( ))
$(select)change(displayVals) displayVals()
CSS
p colorred margin4px b colorblue
HTML
ltpgtltpgt ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt
ltselectgt ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt
ltoption selected=selectedgtMultiple3ltoptiongt ltselectgt
Example 2 Find the value of an input box
Javascript
$(input)keyup(function () var value = $(this)val() $(p)text(value) )keyup()
CSS
p colorblue margin8px
HTML
ltinput type=text value=some textgt ltpgtltpgt
val
Set the value of each element in the set of matched elements
Added in version 14
val(funct ion(index value))jQuery
funct ion(indexvalue)Funct ion
A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the old valueas arguments
This method is typically used to set the values of form f ields
Passing an array of element values allows matching ltinput type=checkboxgt ltinputtype=radiogt and ltopt iongts inside of n ltselect mult iple=mult iplegt to be selected In the caseof ltinput type=radiogts that are part of a radio group and ltselect mult iple=mult iplegt theother elements will be deselected
The val() method allows us to set the value by passing in a funct ion As of jQuery 14 thefunct ion is passed two arguments the current element s index and its current value
$( inputtextitems)val(function(index value) return value + + thisclassName)
This example appends the string items to the text inputs values
Example 1 Set the value of an input box
Javascript
$(button)cl ick(function () var text = $(this)text() $(input)val(text) )
CSS
button margin4px cursorpointer input margin4px colorblue
HTML
ltdivgt ltbuttongtFeedltbuttongt ltbuttongttheltbuttongt
ltbuttongtInputltbuttongt ltdivgt ltinput type=text value=click a button gt
Example 2 Use the funct ion argument to modify the value of an input box
Javascript
$( input)bind(blur function() $(this)val(function(i val) return valtoUpperCase() ) )
HTML
ltpgtType something and then click or tab out of the inputltpgt ltinput type=text value=type something gt
Example 3 Set a single select a mult iple select checkboxes and a radio button
Javascript
$(single)val(Single2) $(multiple)val([Multiple2 Multiple3]) $(input)val([check1check2 radio1 ])
CSS
body colorblue
HTML
ltselect id=singlegt ltoptiongtSingleltoptiongt ltoptiongtSingle2ltoptiongt ltselectgt
ltselect id=multiple multiple=multiplegt ltoption selected=selectedgtMultipleltoptiongt ltoptiongtMultiple2ltoptiongt
ltoption selected=selectedgtMultiple3ltoptiongt ltselectgtltbrgt ltinput type=checkbox name=checkboxname value=check1gt check1 ltinput type=checkbox name=checkboxname value=check2gt check2 ltinput type=radio name=r value=radio1gt radio1 ltinput type=radio name=r value=radio2gt radio2
html
Get the HTML contents of the f irst element in the set of matched elements
Added in version 10
html()String
This method is not available on XML documents
In an HTML document html() can be used to get the contents of any element If the selectorexpression matches more than one element only the f irst match will have its HTML contentreturned Consider this code
$(divdemo-container)html()
In order for the following ltdivgts content to be retrieved it would have to be the f irst one withclass=demo-container in the document
ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt
The result would look like this
ltdiv class=demo-boxgtDemonstration Boxltdivgt
This method uses the browsers innerHTML property Some browsers may not return HTML
that exact ly replicates the HTML source in an original document For example Internet Explorersometimes leaves of f the quotes around at t ribute values if they contain only alphanumericcharacters
Example 1 Click a paragraph to convert it f rom html to text
Javascript
$(p)cl ick(function () var htmlStr = $(this)html() $(this)text(htmlStr) )
CSS
p margin8px font-size20px colorblue cursorpointer b text-decorationunderline button cursorpointer
HTML
ltpgt
ltbgtClickltbgt to change the ltspan id=taggthtmlltspangt ltpgt ltpgt
to a ltspan id=textgttextltspangt node ltpgt ltpgt This ltbutton name=nadagtbuttonltbuttongt does nothing ltpgt
html
Set the HTML contents of each element in the set of matched elements
Added in version 14
html(funct ion(index oldhtml))jQuery
funct ion(indexoldhtml)Funct ion
A funct ion returning the HTML content to set Receives the indexposit ion of the element in the set and the old HTML value asarguments jQuery empt ies the element before calling the funct ionuse the oldhtml argument to reference the previous content Withinthe funct ion this refers to the current element in the set
The html() method is not available in XML documents
When html() is used to set an element s content any content that was in that element iscompletely replaced by the new content Consider the following HTML
ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgtltdivgt
The content of ltdiv class=demo-containergt can be set like this
$(divdemo-container) html(ltpgtAll new content ltemgtYou betltemgtltpgt)
That line of code will replace everything inside ltdiv class=demo-containergt
ltdiv class=demo-containergt ltpgtAll new content ltemgtYou betltemgtltpgtltdivgt
As of jQuery 14 the html() method allows the HTML content to be set by passing in afunct ion
$(divdemo-container)html(function() var emph = ltemgt + $(p)length + paragraphsltemgt return ltpgtAll new content for + emph + ltpgt)
Given a document with six paragraphs this example will set the HTML of ltdiv class=demo-containergt to ltpgtAll new content for ltemgt6 paragraphsltemgtltpgt
This method uses the browsers innerHTML property Some browsers may not generate a DOMthat exact ly replicates the HTML source provided For example Internet Explorer prior toversion 8 will convert all href propert ies on links to absolute URLs and Internet Explorer prior toversion 9 will not correct ly handle HTML5 elements without the addit ion of a separatecompat ibility layer
Example 1 Add some html to each div
Javascript
$(div)html(ltspan class=redgtHello ltbgtAgainltbgtltspangt)
CSS
red colorred
HTML
ltspangtHelloltspangt ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
Example 2 Add some html to each div then immediately do further manipulat ions to theinserted html
Javascript
$(div)html(ltbgtWowltbgt Such excitement) $(div b)append(documentcreateTextNode()) css(color red)
CSS
div colorblue font-size18px
HTML
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
toggleClass
Add or remove one or more classes from each element in the set of matched elementsdepending on either the classs presence or the value of the switch argument
Added in version 14
toggleClass(funct ion(index class switch) switch)jQuery
funct ion(indexclassswitch)Funct ion
A funct ion that returns class names to be toggled in the classattribute of each element in the matched set Receives the indexposit ion of the element in the set the old class value and the switchas arguments
switchBoolean (opt ional) A boolean value to determine whether the class should beadded or removed
This method takes one or more class names as its parameter In the f irst version if an elementin the matched set of elements already has the class then it is removed if an element does nothave the class then it is added For example we can apply toggleClass() to a simple ltdivgt
ltdiv class=tumblegtSome textltdivgt
The f irst t ime we apply $(divtumble)toggleClass(bounce) we get the following
ltdiv class=tumble bouncegtSome textltdivgt
The second t ime we apply $(divtumble)toggleClass(bounce) the ltdivgt class is returned tothe single tumble value
ltdiv class=tumblegtSome textltdivgt
Applying toggleClass(bounce spin) to the same ltdivgt alternates between ltdiv class=tumblebounce spingt and ltdiv class=tumblegt
The second version of toggleClass() uses the second parameter for determining whether theclass should be added or removed If this parameters value is t rue then the class is added iffalse the class is removed In essence the statement
$(foo)toggleClass(className addOrRemove)
is equivalent to
i f (addOrRemove) $(foo)addClass(className) else $(foo)removeClass(className)
As of jQuery 14 if no arguments are passed to toggleClass() all class names on the elementthe f irst t ime toggleClass() is called will be toggled Also as of jQuery 14 the class name to be
toggled can be determined by passing in a funct ion
$(divfoo)toggleClass(function() if ($(this)parent()is( bar)) return happy else return sad )
This example will toggle the happy class for ltdiv class=foogt elements if their parent elementhas a class of bar otherwise it will toggle the sad class
Example 1 Toggle the class highlight when a paragraph is clicked
Javascript
$(p)cl ick(function () $(this)toggleClass(highlight) )
CSS
p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundyellow
HTML
ltp class=bluegtClick to toggleltpgt ltp class=blue highlightgthighlightltpgt ltp class=bluegton theseltpgt ltp class=bluegtparagraphsltpgt
Example 2 Add the highlight class to the clicked paragraph on every third click of thatparagraph remove it every f irst and second click
Javascript
var count = 0$(p)each(function() var $thisParagraph = $(this) var count = 0 $thisParagraphclick(function() count++ $thisParagraphfind(span)text(cl icks + count) $thisParagraphtoggleClass(highlight count 3 == 0) ))
CSS
p margin 4px font-size16px font-weightbolder cursorpointer blue colorblue highlight backgroundred
HTML
ltp class=bluegtClick to toggle (ltspangtclicks 0ltspangt)ltpgt ltp class=blue highlightgthighlight (ltspangtclicks 0ltspangt)ltpgt ltp class=bluegton these (ltspangtclicks 0ltspangt)ltpgt
ltp class=bluegtparagraphs (ltspangtclicks 0ltspangt)ltpgt
Example 3 Toggle the class name(s) indicated on the buttons for each div
CSS
wrap gt div float left width 100px margin 1em 1em 0 0 padding=left 3px border 1px solid abc diva background-color aqua divb background-color burlywood divc background-color cornsilk
HTML
ltdiv class=buttonsgt ltbuttongttoggleltbuttongt ltbutton class=agttoggle altbuttongt ltbutton class=a bgttoggle a bltbuttongt ltbutton class=a b cgttoggle a b cltbuttongt lta href=gtresetltagtltdivgtltdiv class=wrapgt ltdivgtltdivgt ltdiv class=bgtltdivgt ltdiv class=a bgtltdivgt ltdiv class=a cgtltdivgtltdivgt
Javascript
var cls = [ a a b a b c]var divs = $(divwrap)children()var appendClass = function() divsappend(function() return ltdivgt + (thisclassName || none) + ltdivgt )
appendClass()
$(button)bind(cl ick function() var tc = thisclassName || undefined divstoggleClass(tc) appendClass())
$(a)bind(cl ick function(event) eventpreventDefault() divsempty()each(function(i) thisclassName = cls[i] ) appendClass())
removeClass
Remove a single class mult iple classes or all classes from each element in the set of matchedelements
Added in version 14
removeClass(funct ion(index class))jQuery
funct ion(index A funct ion returning one or more space-separated class names to be
class)Funct ion removed Receives the index posit ion of the element in the set and theold class value as arguments
If a class name is included as a parameter then only that class will be removed from the set ofmatched elements If no class names are specif ied in the parameter all classes will be removed
More than one class may be removed at a t ime separated by a space f rom the set of matchedelements like so
$(p)removeClass(myClass yourClass)
This method is of ten used with addClass() to switch elements classes from one to anotherlike so
$(p)removeClass(myClass noClass)addClass(yourClass)
Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded
To replace all exist ing classes with another class we can use at t r(class newClass) instead
As of jQuery 14 the removeClass() method allows us to indicate the class to be removed bypassing in a funct ion
$( l i last)removeClass(function() return $(this)prev()attr(class) )
This example removes the class name of the penult imate ltligt f rom the last ltligt
Example 1 Remove the class blue f rom the matched elements
Javascript
$(peven)removeClass(blue)
CSS
p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow
HTML
ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt
ltp class=blue undergtGoodbyeltpgt
Example 2 Remove the class blue and under f rom the matched elements
Javascript
$(podd)removeClass(blue under)
CSS
p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow
HTML
ltp class=blue undergtHelloltpgt
ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt ltp class=blue undergtGoodbyeltpgt
Example 3 Remove all the classes from the matched elements
Javascript
$(peq(1))removeClass()
CSS
p margin 4px font-size16px font-weightbolder blue colorblue under text-decorationunderline highlight backgroundyellow
HTML
ltp class=blue undergtHelloltpgt ltp class=blue under highlightgtandltpgt ltp class=blue undergtthenltpgt
ltp class=blue undergtGoodbyeltpgt
hasClass
Determine whether any of the matched elements are assigned the given class
Added in version 12
hasClass(className)Boolean
classNameString The class name to search for
Elements may have more than one class assigned to them In HTML this is represented byseparat ing the class names with a space
ltdiv id=mydiv class=foo bargtltdivgt
The hasClass() method will return t rue if the class is assigned to an element even if otherclasses also are For example given the HTML above the following will return t rue
$(mydiv)hasClass(foo)
As would
$(mydiv)hasClass(bar)
While this would return false
$(mydiv)hasClass(quux)
Example 1 Looks for the paragraph that contains selected as a class
Javascript
$(divresult1)append($(pfirst)hasClass(selected)toString())$(divresult2)append($(plast)hasClass(selected)toString())$(divresult3)append($(p)hasClass(selected)toString())
CSS
p margin 8px font-size16px selected colorred
HTML
ltpgtThis paragraph is black and is the first paragraphltpgt ltp class=selectedgtThis paragraph is red and is the second paragraphltpgt
ltdiv id=result1gtFirst paragraph has selected class ltdivgt ltdiv id=result2gtSecond paragraph has selected class ltdivgt ltdiv id=result3gtAt least one paragraph has selected class ltdivgt
removeAttr
Remove an at t ribute f rom each element in the set of matched elements
Added in version 10
removeAttr(at t ributeName)jQuery
attributeNameString An at t ribute to remove
The removeAttr() method uses the JavaScript removeAttribute() funct ion but it has theadvantage of being able to be called direct ly on a jQuery object and it accounts for dif ferentat t ribute naming across browsers
NoteIf at tempt ing to remove an inline onclick event handler using removeAttr() one may f indthat this doesnt achieve the desired ef fect in Internet Explorer 67 or 8 Instead it isrecommended to opt for using prop() to achieve this as follows
$elementprop(onclick null)consolelog(onclick property $element[0]onclick)
We may update the behavior of removeAttr() at some point in the future to better handle thishowever for the t ime being the above should be considered the standard cross-browserapproach to this problem
Example 1 Clicking the button enables the input next to it
Javascript
$(button)cl ick(function () $(this)next()removeAttr(disabled) focus() val(editable now))
HTML
ltbuttongtEnableltbuttongtltinput type=text disabled=disabled value=cant edit this gt
attr
Get the value of an at t ribute for the f irst element in the set of matched elements
Added in version 10
attr(at t ributeName)String
attributeNameString The name of the at t ribute to get
The at t r() method gets the at t ribute value for only the first element in the matched set To getthe value for each element individually use a looping construct such as jQuerys each() ormap() method
As of jQuery 16 the at t r() method returns undef ined for at t ributes that have not been set Inaddit ion at t r() should not be used on plain objects arrays the window or the document Toretrieve and change DOM propert ies use the prop() method
Using jQuerys at t r() method to get the value of an element s at t ribute has two main benef its
1 Convenience It can be called direct ly on a jQuery object and chained to other jQuerymethods
2 Cross-browser consistency The values of some attributes are reported inconsistent lyacross browsers and even across versions of a single browser The at t r() methodreduces such inconsistencies
Note Attribute values are strings with the exception of a few attributes such asvalue and tabindex
Example 1 Find the t it le at t ribute of the f irst in the page
Javascript
var title = $(em)attr(title) $(div)text(title)
CSS
em colorblue font-weightbold div colorred
HTML
ltpgt Once there was a ltem title=huge giganticgtlargeltemgt dinosaurltpgt
The title of the emphasis isltdivgtltdivgt
attr
Set one or more at t ributes for the set of matched elements
Added in version 11
attr(at t ributeName funct ion(index at t r))jQuery
attributeNameString The name of the at t ribute to set
funct ion(indexat t r)Funct ion
A funct ion returning the value to set this is the current elementReceives the index posit ion of the element in the set and the oldattribute value as arguments
The at t r() method is a convenient way to set the value of at t ributesacirceurordquoespecially when sett ingmult iple at t ributes or using values returned by a funct ion Consider the following image
ltimg id=greatphoto src=brush-sellerjpg alt=brush seller gt
Setting a simple attribute
To change the alt at t ribute simply pass the name of the at t ribute and its new value to theat t r() method
$(greatphoto)attr(alt Beij ing Brush Seller)
Add an at t ribute the same way
$(greatphoto)attr(title Photo by Kelly Clark)
Setting several attributes at once
To change the alt at t ribute and add the t it le at t ribute at the same t ime pass both sets ofnames and values into the method at once using a map (JavaScript object literal) Each key-value pair in the map adds or modif ies an at t ribute
$(greatphoto)attr( alt Beij ing Brush Seller title photo by Kelly Clark)
When sett ing mult iple at t ributes the quotes around at t ribute names are opt ional
WARNING When sett ing the class at t ribute you must always use quotes
Note jQuery prohibits changing the type at t ribute on an ltinputgt or ltbuttongt element and willthrow an error in all browsers This is because the type at t ribute cannot be changed in InternetExplorer
Computed attribute values
By using a funct ion to set at t ributes you can compute the value based on other propert ies ofthe element For example to concatenate a new value with an exist ing value
$(greatphoto)attr(title function(i val) return val + - photo by Kelly Clark)
This use of a funct ion to compute at t ribute values can be part icularly useful when modifyingthe at t ributes of mult iple elements at once
Note If nothing is returned in the setter funct ion (ie funct ion(index at t r)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met
Example 1 Set some attributes for all s in the page
Javascript
$(img)attr( src imageshatgif title jQuery alt jQuery Logo)$(div)text($(img)attr(alt))
CSS
img padding10px div colorred font-size24px
HTML
ltimg gt ltimg gt ltimg gt
ltdivgtltBgtAttribute of AjaxltBgtltdivgt
Example 2 Disable buttons greater than the 1st button
Javascript
$(buttongt(1))attr(disableddisabled)
CSS
button margin10px
HTML
ltbuttongt0th Buttonltbuttongt ltbuttongt1st Buttonltbuttongt ltbuttongt2nd Buttonltbuttongt
Example 3 Set the id for divs based on the posit ion in the page
Javascript
$(div)attr( id function (arr) return div-id + arr)each(function () $(span this)html((ID = ltbgt + thisid + ltbgt)))
CSS
div colorblue span colorred b font-weightbolder
HTML
ltdivgtZero-th ltspangtltspangtltdivgt ltdivgtFirst ltspangtltspangtltdivgt ltdivgtSecond ltspangtltspangtltdivgt
Example 4 Set the src at t ribute f rom t it le at t ribute on the image
Javascript
$(img)attr(src function() return images + thistitle )
HTML
ltimg title=hatgifgt
addClass
Adds the specif ied class(es) to each of the set of matched elements
Added in version 14
addClass(funct ion(index currentClass))jQuery
funct ion(indexcurrentClass)Funct ion
A funct ion returning one or more space-separated class namesto be added to the exist ing class name(s) Receives the indexposit ion of the element in the set and the exist ing class name(s)as arguments Within the funct ion this refers to the currentelement in the set
It s important to note that this method does not replace a class It simply adds the classappending it to any which may already be assigned to the elements
More than one class may be added at a t ime separated by a space to the set of matchedelements like so
$(p)addClass(myClass yourClass)
This method is of ten used with removeClass() to switch elements classes from one toanother like so
$(p)removeClass(myClass noClass)addClass(yourClass)
Here the myClass and noClass classes are removed from all paragraphs while yourClass isadded
As of jQuery 14 the addClass() methods argument can receive a funct ion
$(ul l i last)addClass(function() return item- + $(this)index())
Given an unordered list with f ive ltligt elements this example adds the class item-4 to the lastltligt
Example 1 Adds the class selected to the matched elements
Javascript
$(plast)addClass(selected)
CSS
p margin 8px font-size16px selected colorblue highlight backgroundyellow
HTML
ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt
Example 2 Adds the classes selected and highlight to the matched elements
Javascript
$(plast)addClass(selected highlight)
CSS
p margin 8px font-size16px selected colorred highlight backgroundyellow
HTML
ltpgtHelloltpgt ltpgtandltpgt ltpgtGoodbyeltpgt
Example 3 Pass in a funct ion to addClass() to add the green class to a div that already has ared class
Javascript
$(div)addClass(function(index currentClass) var addedClass
i f ( currentClass === red ) addedClass = green $(p)text(There is one green div) return addedClass )
CSS
div background white red background red redgreen background green
HTML
ltdivgtThis div should be whiteltdivgt ltdiv class=redgtThis div wil l be green because it now has the green and red classes It would be red if the addClass function failedltdivgt ltdivgtThis div should be whiteltdivgt ltpgtThere are zero green divsltpgt
CSS
jQuerycssHooks
Hook direct ly into jQuery to override how part icular CSS propert ies are retrieved or set normalize CSS property naming or create custom propert ies
Added in version 143
The $cssHooks object provides a way to def ine funct ions for gett ing and sett ing part icularCSS values It can also be used to create new cssHooks for normalizing CSS3 features such asbox shadows and gradients
For example some versions of Webkit -based browsers require -webkit -border-radius to set theborder-radius on an element while earlier Firefox versions require -moz-border-radius AcssHook can normalize these vendor-pref ixed propert ies to let css() accept a single standardproperty name (border-radius or with DOM property syntax borderRadius)
In addit ion to providing f ine-grained control over how specif ic style propert ies are handled$cssHooks also extends the set of propert ies available to the animate() method
Def ining a new cssHook is straight-forward The skeleton template below can serve as a guideto creat ing your own
(function($) first check to see if cssHooks are supported if ( $cssHooks ) i f not output an error message throw(jQuery 143 or above is required for this plugin to work) return
$cssHooks[someCSSProp] = get function( elem computed extra ) handle getting the CSS property set function( elem value ) handle setting the CSS value )(jQuery)
Feature Testing
Before normalizing a vendor-specif ic CSS property f irst determine whether the browsersupports the standard property or a vendor-pref ixed variat ion For example to check forsupport of the border-radius property see if any variat ion is a member of a temporary
element s style object
(function($) function styleSupport( prop ) var vendorProp supportedProp
capitalize first character of the prop to test vendor prefix capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )
i f ( prop in divstyle )
browser supports standard CSS property name supportedProp = prop else
otherwise test support for vendor-prefixed property names for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break
avoid memory leak in IE div = null add property to $support so it can be accessed elsewhere $support[ prop ] = supportedProp return supportedProp
call the function eg testing for border-radius support styleSupport( borderRadius ))(jQuery)
Defining a complete cssHook
To def ine a complete cssHook combine the support test with a f illed-out version of theskeleton template provided in the f irst example
(function($) if ( $cssHooks ) throw(jQuery 143+ is needed for this plugin to work) return function styleSupport( prop ) var vendorProp supportedProp capProp = propcharAt(0)toUpperCase() + propsl ice(1) prefixes = [ Moz Webkit O ms ] div = documentcreateElement( div )
i f ( prop in divstyle ) supportedProp = prop else for ( var i = 0 i lt prefixeslength i++ ) vendorProp = prefixes[i] + capProp i f ( vendorProp in divstyle ) supportedProp = vendorProp break
div = null $support[ prop ] = supportedProp return supportedProp
var borderRadius = styleSupport( borderRadius )
Set cssHooks only for browsers that support a vendor-prefixed border radius if ( borderRadius ampamp borderRadius == borderRadius ) $cssHookborderRadius = get function( elem computed extra ) return $css( elem borderRadius ) set function( elem value) elemstyle[ borderRadius ] = value )(jQuery)
You can then set the border radius in a supported browser using either the DOM (camelCased)style or the CSS (hyphenated) style
$(element)css(borderRadius 10px)$(another)css(border-radius 20px)
If the browser lacks support for any form of the CSS property vendor-pref ixed or not the styleis not applied to the element However if the browser supports a proprietary alternat ive it canbe applied to the cssHooks instead
(function($) feature test for support of a CSS property and a proprietary alternative
i f ( $supportsomeCSSProp ampamp $supportsomeCSSProp == someCSSProp )
Set cssHooks for browsers that support only a vendor-prefixed someCSSProp $cssHooksomeCSSProp = get function( elem computed extra ) return $css( elem $supportsomeCSSProp ) set function( elem value) elemstyle[ $supportsomeCSSProp ] = value else if ( supportsProprietaryAlternative ) $cssHooksomeCSSProp = get function( elem computed extra ) Handle crazy conversion from the proprietary alternative set function( elem value ) Handle crazy conversion to the proprietary alternative
)(jQuery)
Special units
By default jQuery adds a px unit to the values passed to the css() method This behavior canbe prevented by adding the property to the jQuerycssNumber object
$cssNumber[someCSSProp] = true
Animating with cssHooks
A cssHook can also hook into jQuerys animat ion mechanism by adding a property to thejQueryfxstep object
$fxstep[someCSSProp] = function(fx) $cssHooks[someCSSProp]set( fxelem fxnow + fxunit )
Note that this works best for simple numeric-value animat ions More custom code may berequired depending on the CSS property the type of value it returns and the animat ionscomplexity
outerWidth
Get the current computed width for the f irst element in the set of matched elements includingpadding and border
Added in version 126
outerWidth(includeMargin)Integer
includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion
Returns the width of the element along with lef t and right padding border and opt ionallymargin in pixels
If includeMargin is omit ted or false the padding and border are included in the calculat ion ift rue the margin is also included
This method is not applicable to window and document objects for these use width() instead
Example 1 Get the outerWidth of a paragraph
Javascript
var p = $(pfirst)$(plast)text( outerWidth + pouterWidth()+ outerWidth(true) + pouterWidth(true) )
CSS
p margin10pxpadding5pxborder2px solid 666
HTML
ltpgtHelloltpgtltpgtltpgt
outerHeight
Get the current computed height for the f irst element in the set of matched elements includingpadding border and opt ionally margin
Added in version 126
outerHeight(includeMargin)Integer
includeMarginBoolean (opt ional) A Boolean indicat ing whether to include the element smargin in the calculat ion
The top and bottom padding and border are always included in the outerHeight() calculat ion ifthe includeMargin argument is set to t rue the margin (top and bottom) is also included
This method is not applicable to window and document objects for these use height() instead
Example 1 Get the outerHeight of aparagraph
Javascript
var p = $(pfirst)$(plast)text( outerHeight + pouterHeight() + outerHeight(true) + pouterHeight(true) )
CSS
p margin10pxpadding5pxborder2px solid 666
HTML
ltpgtHelloltpgtltpgtltpgt
innerWidth
Get the current computed width for the f irst element in the set of matched elements includingpadding but not border
Added in version 126
innerWidth()Integer
This method returns the width of the element including lef t and right padding in pixels
This method is not applicable to window and document objects for these use width() instead
Example 1 Get the innerWidth of a paragraph
Javascript
var p = $(pfirst)$(plast)text( innerWidth + pinnerWidth() )
CSS
p margin10pxpadding5pxborder2px solid 666
HTML
ltpgtHelloltpgtltpgtltpgt
innerHeight
Get the current computed height for the f irst element in the set of matched elements includingpadding but not border
Added in version 126
innerHeight()Integer
This method returns the height of the element including top and bottom padding in pixels
This method is not applicable to window and document objects for these use height() instead
Example 1 Get the innerHeight of aparagraph
Javascript
var p = $(pfirst)$(plast)text( innerHeight + pinnerHeight() )
CSS
p margin10pxpadding5pxborder2px solid 666
HTML
ltpgtHelloltpgtltpgtltpgt
width
Get the current computed width for the f irst element in the set of matched elements
Added in version 10
width()Integer
The dif ference between css(width) and width() is that the lat ter returns a unit -less pixel value(for example 400) while the former returns a value with units intact (for example 400px) Thewidth() method is recommended when an element s width needs to be used in a mathematicalcalculat ion
This method is also able to f ind the width of thewindow and document
$(window)width() returns width of browser viewport$(document)width() returns width of HTML document
Note that width() will always return the content width regardless of the value of the CSS box-sizing property
Example 1 Show various widths Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body
Javascript
function showWidth(ele w) $(div)text(The width for the + ele + is + w + px) $(getp)cl ick(function () showWidth(paragraph $(p)width()) ) $(getd)cl ick(function () showWidth(document $(document)width()) ) $(getw)cl ick(function () showWidth(window $(window)width()) )
CSS
body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold
HTML
ltbutton id=getpgtGet Paragraph Widthltbuttongt ltbutton id=getdgtGet Document Widthltbuttongt ltbutton id=getwgtGet Window Widthltbuttongt
ltdivgtampnbspltdivgt ltpgt Sample paragraph to test width ltpgt
width
Set the CSS width of each element in the set of matched elements
Added in version 141
width(funct ion(index width))jQuery
funct ion(indexwidth)Funct ion
A funct ion returning the width to set Receives the index posit ion ofthe element in the set and the old width as arguments Within thefunct ion this refers to the current element in the set
When calling width(value) the value can be either a string (number and unit ) or a number Ifonly a number is provided for the value jQuery assumes a pixel unit If a string is provided
however any valid CSS measurement may be used for the width (such as 100px 50 or auto)Note that in modern browsers the CSS width property does not include padding border ormargin unless the box-sizing CSS property is used
If no explicit unit was specif ied (like em or ) then px is concatenated to the value
Note that width(value) sets the width of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterWidth of the box instead of the content width
Example 1 To set the width of each div on click to 30px plus a color change
Javascript
$(div)one(cl ick function () $(this)width(30) css(cursorauto background-colorblue) )
CSS
div width70px height50px floatleft margin5px backgroundred cursorpointer
HTML
ltdivgtltdivgt ltdivgtdltdivgt
ltdivgtdltdivgt ltdivgtdltdivgt ltdivgtdltdivgt
height
Get the current computed height for the f irst element in the set of matched elements
Added in version 10
height()Integer
The dif ference between css(height ) and height() is that the lat ter returns a unit -less pixelvalue (for example 400) while the former returns a value with units intact (for example 400px)The height() method is recommended when an element s height needs to be used in amathematical calculat ion
This method is also able to f ind the heightof the window and document
$(window)height() returns height of browser viewport$(document)height() returns height of HTML document
Note that height() will always return the content height regardless of the value of the CSSbox-sizing property
Example 1 Show various heights Note the values are f rom the if rame so might be smaller thanyou expected The yellow highlight shows the if rame body
Javascript
function showHeight(ele h) $(div)text(The height for the + ele + is + h + px) $(getp)cl ick(function () showHeight(paragraph $(p)height()) ) $(getd)cl ick(function () showHeight(document $(document)height()) ) $(getw)cl ick(function () showHeight(window $(window)height()) )
CSS
body backgroundyellow button font-size12px margin2px p width150px border1px red solid div colorred font-weightbold
HTML
ltbutton id=getpgtGet Paragraph Heightltbuttongt ltbutton id=getdgtGet Document Heightltbuttongt ltbutton id=getwgtGet Window Heightltbuttongt
ltdivgtampnbspltdivgt ltpgt Sample paragraph to test height ltpgt
height
Set the CSS height of every matched element
Added in version 141
height(funct ion(index height))jQuery
funct ion(indexheight)Funct ion
A funct ion returning the height to set Receives the index posit ion ofthe element in the set and the old height as arguments Within thefunct ion this refers to the current element in the set
When calling height(value) the value can be either a string (number and unit ) or a number Ifonly a number is provided for the value jQuery assumes a pixel unit If a string is providedhowever a valid CSS measurement must be provided for the height (such as 100px 50 orauto) Note that in modern browsers the CSS height property does not include paddingborder or margin
If no explicit unit was specif ied (like em or ) then px is concatenated to the value
Note that height(value) sets the height of the box in accordance with the CSS box-sizingproperty Changing this property to border-box will cause this funct ion to change theouterHeight of the box instead of the content height
Example 1 To set the height of each div on click to 30px plus a color change
Javascript
$(div)one(cl ick function () $(this)height(30) css(cursorauto backgroundColorgreen) )
CSS
div width50px height70px floatleft margin5px backgroundrgb(2551400) cursorpointer
HTML
ltdivgtltdivgt ltdivgtltdivgt
ltdivgtltdivgt ltdivgtltdivgt ltdivgtltdivgt
scrollLeft
Get the current horizontal posit ion of the scroll bar for the f irst element in the set of matchedelements
Added in version 126
scrollLef t ()Integer
The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area If the scroll bar is at the very lef t or if the element is not scrollablethis number will be 0
Example 1 Get the scrollLef t of a paragraph
Javascript
var p = $(pfirst) $(plast)text( scrollLeft + pscrollLeft() )
CSS
p margin10pxpadding5pxborder2px solid 666
HTML
ltpgtHelloltpgtltpgtltpgt
scrollLeft
Set the current horizontal posit ion of the scroll bar for each of the set of matched elements
Added in version 126
scrollLef t (value)jQuery
valueNumber An integer indicat ing the new posit ion to set the scroll bar to
The horizontal scroll posit ion is the same as the number of pixels that are hidden from viewabove the scrollable area Sett ing the scrollLef t posit ions the horizontal scroll of each matchedelement
Example 1 Set the scrollLef t of a div
Javascript
$(divdemo)scrollLeft(300)
CSS
divdemo backgroundCCCCCC none repeat scroll 0 0 border3px solid 666666 margin5px padding5px positionrelative width200px height100px overflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px
HTML
ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt
scrollTop
Get the current vert ical posit ion of the scroll bar for the f irst element in the set of matchedelements
Added in version 126
scrollTop()Integer
The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area If the scroll bar is at the very top or if the element is not scrollable thisnumber will be 0
Example 1 Get the scrollTop of a paragraph
Javascript
var p = $(pfirst)$(plast)text( scrollTop + pscrollTop() )
CSS
p margin10pxpadding5pxborder2px solid 666
HTML
ltpgtHelloltpgtltpgtltpgt
scrollTop
Set the current vert ical posit ion of the scroll bar for each of the set of matched elements
Added in version 126
scrollTop(value)jQuery
valueNumber An integer indicat ing the new posit ion to set the scroll bar to
The vert ical scroll posit ion is the same as the number of pixels that are hidden from view abovethe scrollable area Sett ing the scrollTop posit ions the vert ical scroll of each matched element
Example 1 Set the scrollTop of a div
Javascript
$(divdemo)scrollTop(300)
CSS
divdemo backgroundCCCCCC none repeat scroll 0 0border3px solid 666666margin5pxpadding5pxpositionrelativewidth200pxheight100pxoverflowauto p margin10pxpadding5pxborder2px solid 666width1000pxheight1000px
HTML
ltdiv class=demogtlth1gtlalalalth1gtltpgtHelloltpgtltdivgt
position
Get the current coordinates of the f irst element in the set of matched elements relat ive to theoffset parent
Added in version 12
posit ion()Object
The posit ion() method allows us to retrieve the current posit ion of an element relative to theoffset parent Contrast this with of fset() which retrieves the current posit ion relative to thedocument When posit ioning a new element near another one and within the same containingDOM element posit ion() is the more useful
Returns an object containing the propert ies top and lef t
Example 1 Access the posit ion of the second paragraph
Javascript
var p = $(pfirst)var position = pposition()$(plast)text( left + positionleft + top + positiontop )
CSS
div padding 15px p margin-left10px
HTML
ltdivgt ltpgtHelloltpgtltdivgtltpgtltpgt
offset
Get the current coordinates of the f irst element in the set of matched elements relat ive to thedocument
Added in version 12
offset()Object
The of fset() method allows us to retrieve the current posit ion of an element relative to thedocument Contrast this with posit ion() which retrieves the current posit ion relative to the offsetparent When posit ioning a new element on top of an exist ing one for global manipulat ion (inpart icular for implement ing drag-and-drop) of fset() is the more useful
of fset() returns an object containing the propert ies top and lef t
Note jQuery does not support getting the offset coordinates of hidden elements oraccounting for borders margins or padding set on the body element
Example 1 Access the of fset of the second paragraph
Javascript
var p = $(plast)var offset = poffset()phtml( left + offsetleft + top + offsettop )
CSS
p margin-left10px
HTML
ltpgtHelloltpgtltpgt2nd Paragraphltpgt
Example 2 Click to see the of fset
Javascript
$( documentbody)cl ick(function (e) var offset = $(this)offset() estopPropagation() $(result)text(thistagName + coords ( + offsetleft + + offsettop + )))
CSS
p margin-left10px colorblue width200px cursorpointer span colorred cursorpointer divabs width50px height50px positionabsolute left220px top35px background-colorgreen cursorpointer
HTML
ltdiv id=resultgtClick an elementltdivgtltpgt This is the best way to ltspangtfindltspangt an offsetltpgt
ltdiv class=absgtltdivgt
offset
Set the current coordinates of every element in the set of matched elements relat ive to thedocument
Added in version 14
offset(funct ion(index coords))jQuery
funct ion(indexcoords)Funct ion
A funct ion to return the coordinates to set Receives the index of theelement in the collect ion as the f irst argument and the currentcoordinates as the second argument The funct ion should return anobject with the new top and lef t propert ies
The of fset() set ter method allows us to reposit ion an element The element s posit ion isspecif ied relative to the document If the element s posit ion style property is current ly stat ic it
will be set to relat ive to allow for this reposit ioning
Example 1 Set the of fset of the second paragraph
Javascript
$(plast)offset( top 10 left 30 )
CSS
p margin-left10px
HTML
ltpgtHelloltpgtltpgt2nd Paragraphltpgt
css
Get the value of a style property for the f irst element in the set of matched elements
Added in version 10
css(propertyName)String
propertyNameString A CSS property
The css() method is a convenient way to get a style property f rom the f irst matched elementespecially in light of the dif ferent ways browsers access most of those propert ies (thegetComputedStyle() method in standards-based browsers versus the currentStyle andrunt imeStyle propert ies in Internet Explorer) and the dif ferent terms browsers use for certainpropert ies For example Internet Explorers DOM implementat ion refers to the f loat property asstyleFloat while W3C standards-compliant browsers refer to it as cssFloat The css() methodaccounts for such dif ferences producing the same result no matter which term we use Forexample an element that is f loated lef t will return the string lef t for each of the following threelines
1 $(divlef t )css(f loat )
2 $(divlef t )css(cssFloat )
3 $(divlef t )css(styleFloat )
Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color)and css(backgroundColor) Dif ferent browsers may return CSS color values that are logicallybut not textually equal eg FFF f f f f f f and rgb(255255255)
but not textually equal eg FFF f f f f f f and rgb(255255255)
Shorthand CSS propert ies (eg margin background border) are not supported For example ifyou want to retrieve the rendered margin use $(elem)css(marginTop) and$(elem)css(marginRight ) and so on
Example 1 To access the background color of a clicked div
Javascript
$(div)cl ick(function () var color = $(this)css(background-color) $(result)html(That div is ltspan style=color + color + gt + color + ltspangt))
CSS
div width60px height60px margin5px floatleft
HTML
ltspan id=resultgtampnbspltspangtltdiv style=background-colorbluegtltdivgtltdiv style=background-colorrgb(159930)gtltdivgt
ltdiv style=background-color123456gtltdivgtltdiv style=background-colorf11gtltdivgt
css
Set one or more CSS propert ies for the set of matched elements
Added in version 10
css(map)jQuery
mapMap A map of property-value pairs to set
As with the prop() method the css() method makes sett ing propert ies of elements quick andeasy This method can take either a property name and value as separate parameters or asingle map of key-value pairs (JavaScript object notat ion)
Also jQuery can equally interpret the CSS and DOM formatt ing of mult iple-word propert ies Forexample jQuery understands and returns the correct value for both css(background-color
f fe border-lef t 5px solid ccc) and css(backgroundColor f fe borderLeft 5px solidccc) Not ice that with the DOM notat ion quotat ion marks around the property names areopt ional but with CSS notat ion theyre required due to the hyphen in the name
When using css() as a setter jQuery modif ies the element s style property For example$(mydiv)css(color green) is equivalent to documentgetElementById(mydiv)stylecolor =green Sett ing the value of a style property to an empty string acirceurordquo eg $(mydiv)css(color )acirceurordquo removes that property f rom an element if it has already been direct ly applied whether in theHTML style at t ribute through jQuerys css() method or through direct DOM manipulat ion ofthe style property It does not however remove a style that has been applied with a CSS rule ina stylesheet or ltstylegt element
As of jQuery 16 css() accepts relat ive values similar to animate() Relat ive values are a stringstart ing with += or -= to increment or decrement the current value For example if an element spadding-lef t was 10px css( padding-lef t +=15 ) would result in a total padding-lef t of 25px
As of jQuery 14 css() allows us to pass a funct ion as the property value
$(divexample)css(width function(index) return index 50)
This example sets the widths of the matched elements to incrementally larger values
Note If nothing is returned in the setter funct ion (ie funct ion(index style)) or if undef ined isreturned the current value is not changed This is useful for select ively set t ing values onlywhen certain criteria are met
Example 1 To change the color of any paragraph to red on mouseover event
Javascript
$(p)mouseover(function () $(this)css(colorred) )
CSS
p colorblue width200px font-size14px
HTML
ltpgtJust roll the mouse over meltpgt
ltpgtOr me to see a color changeltpgt
Example 2 Increase the width of box by 200 pixels
Javascript
$(box)one( cl ick function () $( this )css( width+=200 ) )
CSS
box background black color snow width100px padding10px
HTML
ltdiv id=boxgtClick me to growltdivgt
Example 3 To highlight a clicked word in the paragraph
Javascript
var words = $(pfirst)text()split( ) var text = wordsjoin(ltspangt ltspangt) $(pfirst)html(ltspangt + text + ltspangt) $(span)cl ick(function () $(this)css(background-coloryellow) )
CSS
p colorblue font-weightbold cursorpointer
HTML
ltpgt Once upon a time there was a man who l ived in a pizza parlor This man just loved pizza and ate it al l the time He went on to be the happiest man in the world The endltpgt
Example 4 To set the color of all paragraphs to red and background to blue
Javascript
$(p)hover(function () $(this)css(background-color yellow font-weight bolder) function () var cssObj = background-color ddd font-weight color rgb(040244) $(this)css(cssObj) )
CSS
p colorgreen
HTML
ltpgtMove the mouse over a paragraphltpgt ltpgtLike this one or the one aboveltpgt
Example 5 Increase the size of a div when you click it
Javascript
$(div)cl ick(function() $(this)css( width function(index value) return parseFloat(value) 12 height function(index value) return parseFloat(value) 12
) )
CSS
div width 20px height 15px background-color f33
HTML
ltdivgtclickltdivgt ltdivgtclickltdivgt
toggleClass see Attributes
removeClass see Attributes
hasClass see Attributes
addClass see Attributes
Manipulation
removeProp see Attributes
prop see Attributes
prop see Attributes
outerWidth see CSS
outerHeight see CSS
innerWidth see CSS
innerHeight see CSS
width see CSS
width see CSS
height see CSS
height see CSS
scrollLeft see CSS
scrollLeft see CSS
scrollTop see CSS
scrollTop see CSS
position see CSS
offset see CSS
offset see CSS
css see CSS
css see CSS
unwrap
Remove the parents of the set of matched elements f rom the DOM leaving the matchedelements in their place
Added in version 14
unwrap()jQuery
The unwrap() method removes the element s parent This is ef fect ively the inverse of thewrap() method The matched elements (and their siblings if any) replace their parents withinthe DOM structure
Example 1 Wrapunwrap a div around each of the paragraphs
Javascript
$(button)toggle(function() $(p)wrap(ltdivgtltdivgt) function() $(p)unwrap())
CSS
div border 2px solid blue p backgroundyellow margin4px
HTML
ltbuttongtwrapunwrapltbuttongtltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt
detach
Remove the set of matched elements f rom the DOM
Added in version 14
detach(selector)jQuery
selectorSelector (opt ional) A selector expression that f ilters the set of matchedelements to be removed
The detach() method is the same as remove() except that detach() keeps all jQuery dataassociated with the removed elements This method is useful when removed elements are tobe reinserted into the DOM at a later t ime
Example 1 Detach all paragraphs from the DOM
Javascript
$(p)cl ick(function() $(this)toggleClass(off) ) var p $(button)cl ick(function() i f ( p ) pappendTo(body) p = null else p = $(p)detach() )
CSS
p backgroundyellow margin6px 0 poff background black
HTML
ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtAttachdetach paragraphsltbuttongt
clone
Create a deep copy of the set of matched elements
Added in version 15
clone(withDataAndEvents deepWithDataAndEvents)jQuery
withDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data should be copied along with the
elements The default value is false In jQuery 150the default value was incorrectly true it was changedback to false in 151 and up
deepWithDataAndEventsBoolean (opt ional) A Boolean indicat ing whether eventhandlers and data for all children of the clonedelement should be copied By default its valuematches the f irst argument s value (which defaultsto false)
The clone() method performs a deep copy of the set of matched elements meaning that itcopies the matched elements as well as all of their descendant elements and text nodes Whenused in conjunct ion with one of the insert ion methods clone() is a convenient way to duplicateelements on a page Consider the following HTML
ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt
As shown in the discussion for append() normally when an element is inserted somewhere inthe DOM it is moved from its old locat ion So given the code
$(hello)appendTo(goodbye)
The result ing DOM structure would be
ltdiv class=containergt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt
To prevent this and instead create a copy of the element you could write the following
$(hello)clone()appendTo(goodbye)
This would produce
ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegt Goodbye ltdiv class=hellogtHelloltdivgt ltdivgtltdivgt
Note that when using the clone() method you can modify the cloned elements ortheir contents before (re-)inserting them into the document
Normally any event handlers bound to the original element are not copied to the clone Theopt ional withDataAndEvents parameter allows us to change this behavior and to instead makecopies of all of the event handlers as well bound to the new copy of the element As of jQuery14 all element data (at tached by the data() method) is also copied to the new copy
However objects and arrays within element data are not copied and will cont inue to be sharedbetween the cloned element and the original element To deep copy all data copy each onemanually
var $elem = $(elem)data( arr [ 1 ] ) Original element with attached data $clone = $elemclone( true ) data( arr $extend( [] $elemdata(arr) ) ) Deep copy to prevent data sharing
As of jQuery 15 withDataAndEvents can be opt ionally enhanced withdeepWithDataAndEvents to copy the events and data for all children of the cloned element
Example 1 Clones all b elements (and selects the clones) and prepends them to all paragraphs
Javascript
$(b)clone()prependTo(p)
HTML
ltbgtHelloltbgtltpgt how are youltpgt
Example 2 When using clone() to clone a collect ion of elements that are not at tached to theDOM their order when inserted into the DOM is not guaranteed However it may be possible topreserve sort order with a workaround as demonstrated
CSS
orig copy copy-correct float left width 20
Javascript
sort order is not guaranteed here and may vary with browser $(copy)append($(orig elem) clone() children(a) prepend(foo - ) parent() clone()) correct way to approach where order is maintained$(copy-correct) append($(orig elem) clone() children(a) prepend(bar - ) end())
HTML
ltdiv id=origgt ltdiv class=elemgtltagt1ltagtltdivgt ltdiv class=elemgtltagt2ltagtltdivgt ltdiv class=elemgtltagt3ltagtltdivgt ltdiv class=elemgtltagt4ltagtltdivgt ltdiv class=elemgtltagt5ltagtltdivgtltdivgtltdiv id=copygtltdivgtltdiv id=copy-correctgtltdivgt
remove
Remove the set of matched elements f rom the DOM
Added in version 10
remove(selector)jQuery
selectorString (opt ional) A selector expression that f ilters the set of matchedelements to be removed
Similar to empty() the remove() method takes elements out of the DOM Use remove() when
you want to remove the element itself as well as everything inside it In addit ion to theelements themselves all bound events and jQuery data associated with the elements areremoved To remove the elements without removing data and events use detach() instead
Consider the following HTML
ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt
We can target any element for removal
$(hello)remove()
This will result in a DOM structure with the ltdivgt element deleted
ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt
If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo Other jQuery constructs such as data or event handlers are erased as well
We can also include a selector as an opt ional parameter For example we could rewrite theprevious DOM removal code as follows
$(div)remove(hello)
This would result in the same DOM structure
ltdiv class=containergt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt
Example 1 Removes all paragraphs from the DOM
Javascript
$(button)cl ick(function () $(p)remove() )
CSS
p backgroundyellow margin6px 0
HTML
ltpgtHelloltpgt how are ltpgtyoultpgt ltbuttongtCall remove() on paragraphsltbuttongt
Example 2 Removes all paragraphs that contain Hello f rom the DOM Analogous to doing$(p)f ilter(contains(Hello))remove()
Javascript
$(button)cl ick(function () $(p)remove(contains(Hello)) )
CSS
p backgroundyellow margin6px 0
HTML
ltp class=hellogtHelloltpgt how are ltpgtyoultpgt
ltbuttongtCall remove(contains(Hello)) on paragraphsltbuttongt
empty
Remove all child nodes of the set of matched elements f rom the DOM
Added in version 10
empty()jQuery
This method removes not only child (and other descendant) elements but also any text withinthe set of matched elements This is because according to the DOM specif icat ion any stringof text within an element is considered a child node of that element Consider the followingHTML
ltdiv class=containergt ltdiv class=hellogtHelloltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt
We can target any element for removal
$(hello)empty()
This will result in a DOM structure with the Hello text deleted
ltdiv class=containergt ltdiv class=hellogtltdivgt ltdiv class=goodbyegtGoodbyeltdivgtltdivgt
If we had any number of nested elements inside ltdiv class=hellogt they would be removedtoo
To avoid memory leaks jQuery removes other constructs such as data and event handlersfrom the child elements before removing the elements themselves
Example 1 Removes all child nodes (including text nodes) f rom all paragraphs
Javascript
$(button)cl ick(function () $(p)empty() )
CSS
p backgroundyellow
HTML
ltpgt Hello ltspangtPersonltspangt lta href=javascriptgtand personltagtltpgt
ltbuttongtCall empty() on above paragraphltbuttongt
replaceAll
Replace each target element with the set of matched elements
Added in version 12
replaceAll(target)jQuery
targetSelector A selector expression indicat ing which element(s) to replace
The replaceAll() method is corollary to replaceWith() but with the source and target reversedConsider this DOM structure
ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt
We can create an element then replace other elements with it
$(lth2gtNew headinglth2gt)replaceAll( inner)
This causes all of them to be replaced
ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt
Or we could select an element to use as the replacement
$(first)replaceAll( third)
This results in the DOM structure
ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt
From this example we can see that the selected element replaces the target by being movedfrom its old locat ion not by being cloned
Example 1 Replace all the paragraphs with bold words
Javascript
$(ltbgtParagraph ltbgt)replaceAll(p) check replaceWith() examples
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
replaceWith
Replace each element in the set of matched elements with the provided new content
Added in version 14
replaceWith(funct ion)jQuery
funct ionFunct ion A funct ion that returns content with which to replace the set ofmatched elements
The replaceWith() method removes content f rom the DOM and inserts new content in its placewith a single call Consider this DOM structure
ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt
The second inner ltdivgt could be replaced with the specif ied HTML
$(divsecond)replaceWith(lth2gtNew headinglth2gt)
This results in the structure
ltdiv class=containergt ltdiv class=inner firstgtHelloltdivgt lth2gtNew headinglth2gt ltdiv class=inner thirdgtGoodbyeltdivgtltdivgt
All inner ltdivgt elements could be targeted at once
$(divinner)replaceWith(lth2gtNew headinglth2gt)
This causes all of them to be replaced
ltdiv class=containergt lth2gtNew headinglth2gt lth2gtNew headinglth2gt lth2gtNew headinglth2gtltdivgt
An element could also be selected as the replacement
$(divthird)replaceWith($(first))
This results in the DOM structure
ltdiv class=containergt ltdiv class=inner secondgtAndltdivgt ltdiv class=inner firstgtHelloltdivgtltdivgt
This example demonstrates that the selected element replaces the target by being moved fromits old locat ion not by being cloned
The replaceWith() method like most jQuery methods returns the jQuery object so that othermethods can be chained onto it However it must be noted that the original jQuery object isreturned This object refers to the element that has been removed from the DOM not the newelement that has replaced it
As of jQuery 14 replaceWith() can also work on disconnected DOM nodes For example withthe following code replaceWith() returns a jQuery set containing only a paragraph
$(ltdivgt)replaceWith(ltpgtltpgt)
The replaceWith() method can also take a funct ion as its argument
$(divcontainer)replaceWith(function() return $(this)contents())
This results in ltdiv class=containergt being replaced by its three child ltdivgts The return valueof the funct ion may be an HTML string DOM element or jQuery object
Example 1 On click replace the button with a div containing the same word
Javascript
$(button)cl ick(function () $(this)replaceWith( ltdivgt + $(this)text() + ltdivgt ))
CSS
button displayblock margin3px colorred width200px div colorred border2px solid blue width200px margin3px text-aligncenter
HTML
ltbuttongtFirstltbuttongtltbuttongtSecondltbuttongtltbuttongtThirdltbuttongt
Example 2 Replace all paragraphs with bold words
Javascript
$(p)replaceWith( ltbgtParagraph ltbgt )
HTML
ltpgtHelloltpgtltpgtcruelltpgtltpgtWorldltpgt
Example 3 On click replace each paragraph with a div that is already in the DOM and selectedwith the $() funct ion Not ice it doesnt clone the object but rather moves it to replace theparagraph
Javascript
$(p)cl ick(function () $(this)replaceWith( $(div) ))
CSS
div border2px solid blue colorred margin3px p border2px solid red colorblue margin3px cursorpointer
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
ltdivgtReplacedltdivgt
Example 4 On button click replace the containing div with its child divs and append the classname of the selected element to the paragraph
Javascript
$(button)bind(click function() var $container = $(divcontainer)replaceWith(function() return $(this)contents() )
$(p)append( $containerattr(class) ))
CSS
container background-color 991 inner color 911
HTML
ltpgt ltbuttongtReplaceltbuttongtltpgtltdiv class=containergt ltdiv class=innergtScoobyltdivgt ltdiv class=innergtDoobyltdivgt ltdiv class=innergtDooltdivgtltdivgt
wrapInner
Wrap an HTML structure around the content of each element in the set of matched elements
Added in version 14
wrapInner(funct ion(index))jQuery
funct ion(index)Funct ion A callback funct ion which generates a structure to wraparound the content of the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset
The wrapInner() funct ion can take any string or object that could be passed to the $() factoryfunct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element The structure will be wrapped around the content ofeach of the elements in the set of matched elements
Consider the following HTML
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
Using wrapInner() we can insert an HTML structure around the content of each inner ltdivgtelements like so
$(inner)wrapInner(ltdiv class=new gt)
The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around the content of each matched element
ltdiv class=containergt ltdiv class=innergt ltdiv class=newgtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=newgtGoodbyeltdivgt ltdivgtltdivgt
The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the content of the correspondingelement For example
$(inner)wrapInner(function() return ltdiv class= + thisnodeValue + gt)
This will cause each ltdivgt to have a class corresponding to the text it wraps
ltdiv class=containergt ltdiv class=innergt ltdiv class=HellogtHelloltdivgt ltdivgt ltdiv class=innergt ltdiv class=GoodbyegtGoodbyeltdivgt ltdivgtltdivgt
Note When passing a selector string to the wrapInner() funct ion the expected input is wellformed HTML with correct ly closed tags Examples of valid input include
$(elem)wrapInner(ltdiv class=test gt)$(elem)wrapInner(ltdiv class=testgtltdivgt)$(elem)wrapInner(ltdiv class=testgtltdivgt)
Example 1 Selects all paragraphs and wraps a bold tag around each of its contents
Javascript
$(p)wrapInner(ltbgtltbgt)
CSS
p backgroundbbf
HTML
ltpgtHelloltpgt
ltpgtcruelltpgt ltpgtWorldltpgt
Example 2 Wraps a newly created tree of objects around the inside of the body
Javascript
$(body)wrapInner(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)
CSS
div border2px green solid margin2px padding2px p backgroundyellow margin2px padding2px
HTML
Plain old text or is it
Example 3 Selects all paragraphs and wraps a bold tag around each of its contents
Javascript
$(p)wrapInner(documentcreateElement(b))
CSS
p background9f9
HTML
ltpgtHelloltpgt
ltpgtcruelltpgt ltpgtWorldltpgt
Example 4 Selects all paragraphs and wraps a jQuery object around each of its contents
Javascript
$(p)wrapInner($(ltspan class=redgtltspangt))
CSS
p background9f9 red colorred
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
wrapAll
Wrap an HTML structure around all elements in the set of matched elements
Added in version 12
wrapAll(wrappingElement)jQuery
wrappingElementStringSelector ElementjQuery
An HTML snippet selector expression jQuery object or DOMelement specifying the structure to wrap around the matchedelements
The wrapAll() funct ion can take any string or object that could be passed to the $() funct ion tospecify a DOM structure This structure may be nested several levels deep but should containonly one inmost element The structure will be wrapped around all of the elements in the set ofmatched elements as a single group
Consider the following HTML
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
Using wrapAll() we can insert an HTML structure around the inner ltdivgt elements like so
$(inner)wrapAll(ltdiv class=new gt)
The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around all matched elements
ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt
Example 1 Wrap a new div around all of the paragraphs
Javascript
$(p)wrapAll(ltdivgtltdivgt)
CSS
div border 2px solid blue p backgroundyellow margin4px
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html
Javascript
$(span)wrapAll(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)
CSS
div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred
HTML
ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt
Example 3 Wrap a new div around all of the paragraphs
Javascript
$(p)wrapAll(documentcreateElement(div))
CSS
div border 2px solid blue p backgroundyellow margin4px
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target
Javascript
$(p)wrapAll($(doublediv))
CSS
div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt
wrap
Wrap an HTML structure around each element in the set of matched elements
Added in version 14
wrap(funct ion(index))jQuery
funct ion(index)Funct ion A callback funct ion returning the HTML content or jQueryobject to wrap around the matched elements Receives theindex posit ion of the element in the set as an argumentWithin the funct ion this refers to the current element in theset
The wrap() funct ion can take any string or object that could be passed to the $() factory
funct ion to specify a DOM structure This structure may be nested several levels deep butshould contain only one inmost element A copy of this structure will be wrapped around eachof the elements in the set of matched elements This method returns the original set ofelements for chaining purposes
Consider the following HTML
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
Using wrap() we can insert an HTML structure around the inner ltdivgt elements like so
$(inner)wrap(ltdiv class=new gt)
The new ltdivgt element is created on the f ly and added to the DOM The result is a new ltdivgtwrapped around each matched element
ltdiv class=containergt ltdiv class=newgt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=newgt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt
The second version of this method allows us to instead specify a callback funct ion Thiscallback funct ion will be called once for every matched element it should return a DOMelement jQuery object or HTML snippet in which to wrap the corresponding element Forexample
$(inner)wrap(function() return ltdiv class= + $(this)text() + gt)
This will cause each ltdivgt to have a class corresponding to the text it wraps
ltdiv class=containergt ltdiv class=Hellogt ltdiv class=innergtHelloltdivgt ltdivgt ltdiv class=Goodbyegt ltdiv class=innergtGoodbyeltdivgt ltdivgtltdivgt
Example 1 Wrap a new div around all of the paragraphs
Javascript
$(p)wrap(ltdivgtltdivgt)
CSS
div border 2px solid blue p backgroundyellow margin4px
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
Example 2 Wraps a newly created tree of objects around the spans Not ice anything inbetween the spans gets lef t out like the (red text) in this example Even the white spacebetween spans is lef t out Click View Source to see the original html
Javascript
$(span)wrap(ltdivgtltdivgtltpgtltemgtltbgtltbgtltemgtltpgtltdivgtltdivgt)
CSS
div border2px blue solid margin2px padding2px p backgroundyellow margin2px padding2px strong colorred
HTML
ltspangtSpan Textltspangt ltstronggtWhat about meltstronggt ltspangtAnother Oneltspangt
Example 3 Wrap a new div around all of the paragraphs
Javascript
$(p)wrap(documentcreateElement(div))
CSS
div border 2px solid blue p backgroundyellow margin4px
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt
Example 4 Wrap a jQuery object double depth div around all of the paragraphs Not ice itdoesnt move the object but just clones it to wrap around its target
Javascript
$(p)wrap($(doublediv))
CSS
div border 2px solid blue margin2px padding2px doublediv border-colorred p backgroundyellow margin4px font-size14px
HTML
ltpgtHelloltpgt ltpgtcruelltpgt ltpgtWorldltpgt ltdiv class=doubledivgtltdivgtltdivgtltdivgt
insertBefore
Insert every element in the set of matched elements before the target
Added in version 10
insertBefore(target)jQuery
targetSelectorElementjQuery
A selector element HTML string or jQuery object the matched set ofelements will be inserted before the element(s) specif ied by thisparameter
The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container
Consider the following HTML
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
We can create content and insert it before several elements at once
$(ltpgtTestltpgt)insertBefore(inner)
Each inner ltdivgt element gets this new content
ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt
We can also select an element on the page and insert it before another
$(h2)insertBefore($(container))
If an element selected this way is inserted elsewhere it will be moved before the target (notcloned)
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
Example 1 Inserts all paragraphs before an element with id of foo Same as$( foo)before(p)
Javascript
$(p)insertBefore(foo) check before() examples
CSS
foo backgroundyellow
HTML
ltdiv id=foogtFOOltdivgtltpgtI would l ike to say ltpgt
before
Insert content specif ied by the parameter before each element in the set of matchedelements
Added in version 14
before(funct ion)jQuery
funct ionFunct ion A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert before each element in the set of matched elementsReceives the index posit ion of the element in the set as anargument Within the funct ion this refers to the current element inthe set
The before() and insertBefore() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With before() the selectorexpression preceding the method is the container before which the content is inserted WithinsertBefore() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted before the target container
Consider the following HTML
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
You can create content and insert it before several elements at once
$(inner)before(ltpgtTestltpgt)
Each inner ltdivgt element gets this new content
ltdiv class=containergt lth2gtGreetingslth2gt ltpgtTestltpgt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgtltdivgt
You can also select an element on the page and insert it before another
$(container)before($(h2))
If an element selected this way is inserted elsewhere it will be moved before the target (notcloned)
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
In jQuery 14 before() and af ter() will also work on disconnected DOM nodes
$(ltdivgt)before(ltpgtltpgt)
The result is a jQuery set that contains a paragraph and a div (in that order)
Additional Arguments
Similar to other content-adding methods such as prepend() and af ter() before() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements
For example the following will insert two new ltdivgts and an exist ing ltdivgt before the f irstparagraph
var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)
$(p)first()before($newdiv1 [newdiv2 existingdiv1])
Since before() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so$(p)f irst()before($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code
Example 1 Inserts some HTML before all paragraphs
Javascript
$(p)before(ltbgtHelloltbgt)
CSS
p backgroundyellow
HTML
ltpgt is what I saidltpgt
Example 2 Inserts a DOM element before all paragraphs
Javascript
$(p)before( documentcreateTextNode(Hello) )
CSS
p backgroundyellow
HTML
ltpgt is what I saidltpgt
Example 3 Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs
Javascript
$(p)before( $(b) )
CSS
p backgroundyellow
HTML
ltpgt is what I saidltpgtltbgtHelloltbgt
insertAfter
Insert every element in the set of matched elements af ter the target
Added in version 10
insertAfter(target)jQuery
targetSelectorElementjQuery
A selector element HTML string or jQuery object the matched set ofelements will be inserted af ter the element(s) specif ied by thisparameter
The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container
Consider the following HTML
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
We can create content and insert it af ter several elements at once
$(ltpgtTestltpgt)insertAfter( inner)
Each inner ltdivgt element gets this new content
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt
We can also select an element on the page and insert it af ter another
$(h2)insertAfter($(container))
If an element selected this way is inserted elsewhere it will be moved af ter the target (notcloned)
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
Example 1 Inserts all paragraphs af ter an element with id of foo Same as $( foo)af ter(p)
Javascript
$(p)insertAfter(foo) check after() examples
CSS
foo backgroundyellow
HTML
ltpgt is what I said ltpgtltdiv id=foogtFOOltdivgt
after
Insert content specif ied by the parameter af ter each element in the set of matched elements
Added in version 14
after(funct ion(index))jQuery
funct ion(index)Funct ion A funct ion that returns an HTML string DOM element(s) orjQuery object to insert af ter each element in the set ofmatched elements Receives the index posit ion of theelement in the set as an argument Within the funct ion thisrefers to the current element in the set
The af ter() and insertAfter() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With af ter() the selectorexpression preceding the method is the container af ter which the content is inserted WithinsertAfter() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted af ter the target container
Using the following HTML
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
Content can be created and then inserted af ter several elements at once
$(inner)after(ltpgtTestltpgt)
Each inner ltdivgt element gets this new content
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltpgtTestltpgt ltdiv class=innergtGoodbyeltdivgt ltpgtTestltpgtltdivgt
An element in the DOM can also be selected and inserted af ter another element
$(container)after($(h2))
If an element selected this way is inserted elsewhere it will be moved rather than cloned
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgtlth2gtGreetingslth2gt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
Inserting Disconnected DOM nodes
As of jQuery 14 before() and af ter() will also work on disconnected DOM nodes For examplegiven the following code
$(ltdivgt)after(ltpgtltpgt)
The result is a jQuery set containing a div and a paragraph in that order That set can befurther manipulated even before it is inserted in the document
$(ltdivgt)after(ltpgtltpgt)addClass(foo) fi lter(p)attr( id bar)html(hello)end()appendTo(body)
This results in the following elements inserted just before the closing ltbodygt tag
ltdiv class=foogtltdivgtltp class=foo id=bargthelloltpgt
Passing a Function
As of jQuery 14 af ter() supports passing a funct ion that returns the elements to insert
$(p)after(function() return ltdivgt + thisclassName + ltdivgt)
This example inserts a ltdivgt af ter each paragraph with each new ltdivgt containing the class
name(s) of its preceding paragraph
Additional Arguments
Similar to other content-adding methods such as prepend() and before() af ter() also supportspassing in mult iple arguments as input Supported input includes DOM elements jQuery objectsHTML strings and arrays of DOM elements
For example the following will insert two new ltdivgts and an exist ing ltdivgt af ter the f irstparagraph
var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)
$(p)first()after($newdiv1 [newdiv2 existingdiv1])
Since af ter() can accept any number of addit ional arguments the same result can be achievedby passing in the three ltdivgts as three separate arguments like so $(p)f irst()af ter($newdiv1newdiv2 exist ingdiv1) The type and number of arguments will largely depend on the elementsare collected in the code
Example 1 Inserts some HTML after all paragraphs
Javascript
$(p)after(ltbgtHelloltbgt)
CSS
p backgroundyellow
HTML
ltpgtI would l ike to say ltpgt
Example 2 Inserts a DOM element af ter all paragraphs
Javascript
$(p)after( documentcreateTextNode(Hello) )
CSS
p backgroundyellow
HTML
ltpgtI would l ike to say ltpgt
Example 3 Inserts a jQuery object (similar to an Array of DOM Elements) af ter all paragraphs
Javascript
$(p)after( $(b) )
CSS
p backgroundyellow
HTML
ltbgtHelloltbgtltpgtI would l ike to say ltpgt
prependTo
Insert every element in the set of matched elements to the beginning of the target
Added in version 10
prependTo(target)jQuery
targetSelectorElementjQuery
A selector element HTML string or jQuery object the matched set ofelements will be inserted at the beginning of the element(s) specif iedby this parameter
The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container
Consider the following HTML
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
We can create content and insert it into several elements at once
$(ltpgtTestltpgt)prependTo(inner)
Each inner ltdivgt element gets this new content
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt
We can also select an element on the page and insert it into another
$(h2)prependTo($(container))
If an element selected this way is inserted elsewhere it will be moved into the target (notcloned)
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
Example 1 Prepends all spans to the element with the ID foo
CSS
div backgroundyellow
Javascript
$(span)prependTo(foo) check prepend() examples
HTML
ltdiv id=foogtFOOltdivgt
ltspangtI have something to say ltspangt
prepend
Insert content specif ied by the parameter to the beginning of each element in the set ofmatched elements
Added in version 14
prepend(funct ion(index html))jQuery
funct ion(indexhtml)Funct ion
A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the beginning of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set
The prepend() method inserts the specif ied content as the f irst child of each element in thejQuery collect ion (To insert it as the last child use append())
The prepend() and prependTo() methods perform the same task The major dif ference is in thesyntaxacirceurordquospecif ically in the placement of the content and target With prepend() the selectorexpression preceding the method is the container into which the content is inserted WithprependTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container
Consider the following HTML
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
You can create content and insert it into several elements at once
$(inner)prepend(ltpgtTestltpgt)
Each ltdiv class=innergt element gets this new content
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt ltpgtTestltpgt Hello ltdivgt ltdiv class=innergt ltpgtTestltpgt Goodbye ltdivgtltdivgt
You can also select an element on the page and insert it into another
$(container)prepend($(h2))
If a single element selected this way is inserted elsewhere it will be moved into the target (notcloned)
ltdiv class=containergt lth2gtGreetingslth2gt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
Important If there is more than one target element however cloned copies of the insertedelement will be created for each target af ter the f irst
Additional Arguments
Similar to other content-adding methods such as append() and before() prepend() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements
For example the following will insert two new ltdivgts and an exist ing ltdivgt as the f irst threechild nodes of the body
var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)
$(body)prepend($newdiv1 [newdiv2 existingdiv1])
Since prepend() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so
$(body)prepend($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code
Example 1 Prepends some HTML to all paragraphs
Javascript
$(p)prepend(ltbgtHello ltbgt)
CSS
p backgroundyellow
HTML
ltpgtthere friendltpgt
ltpgtamigoltpgt
Example 2 Prepends a DOM Element to all paragraphs
Javascript
$(p)prepend(documentcreateTextNode(Hello ))
CSS
p backgroundyellow
HTML
ltpgtis what Id sayltpgtltpgtis what I saidltpgt
Example 3 Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs
Javascript
$(p)prepend( $(b) )
CSS
p backgroundyellow
HTML
ltpgt is what was saidltpgtltbgtHelloltbgt
appendTo
Insert every element in the set of matched elements to the end of the target
Added in version 10
appendTo(target)jQuery
targetSelectorElementjQuery
A selector element HTML string or jQuery object the matched set ofelements will be inserted at the end of the element(s) specif ied by thisparameter
The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container
Consider the following HTML
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
We can create content and insert it into several elements at once
$(ltpgtTestltpgt)appendTo(inner)
Each inner ltdivgt element gets this new content
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt
We can also select an element on the page and insert it into another
$(h2)appendTo($(container))
If an element selected this way is inserted elsewhere it will be moved into the target (notcloned)
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
Example 1 Appends all spans to the element with the ID foo
Javascript
$(span)appendTo(foo) check append() examples
CSS
foo backgroundyellow
HTML
ltspangtI have nothing more to say ltspangt
ltdiv id=foogtFOO ltdivgt
append
Insert content specif ied by the parameter to the end of each element in the set of matchedelements
Added in version 14
append(funct ion(index html))jQuery
funct ion(indexhtml)Funct ion
A funct ion that returns an HTML string DOM element(s) or jQueryobject to insert at the end of each element in the set of matchedelements Receives the index posit ion of the element in the set and theold HTML value of the element as arguments Within the funct ion thisrefers to the current element in the set
The append() method inserts the specif ied content as the last child of each element in thejQuery collect ion (To insert it as the first child use prepend())
The append() and appendTo() methods perform the same task The major dif ference is in thesyntax-specif ically in the placement of the content and target With append() the selectorexpression preceding the method is the container into which the content is inserted WithappendTo() on the other hand the content precedes the method either as a selectorexpression or as markup created on the f ly and it is inserted into the target container
Consider the following HTML
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgtltdivgt
You can create content and insert it into several elements at once
$(inner)append(ltpgtTestltpgt)
Each inner ltdivgt element gets this new content
lth2gtGreetingslth2gtltdiv class=containergt ltdiv class=innergt Hello ltpgtTestltpgt ltdivgt ltdiv class=innergt Goodbye ltpgtTestltpgt ltdivgtltdivgt
You can also select an element on the page and insert it into another
$(container)append($(h2))
If an element selected this way is inserted elsewhere it will be moved into the target (notcloned)
ltdiv class=containergt ltdiv class=innergtHelloltdivgt ltdiv class=innergtGoodbyeltdivgt lth2gtGreetingslth2gtltdivgt
If there is more than one target element however cloned copies of the inserted element will becreated for each target af ter the f irst
Additional Arguments
Similar to other content-adding methods such as prepend() and before() append() alsosupports passing in mult iple arguments as input Supported input includes DOM elementsjQuery objects HTML strings and arrays of DOM elements
For example the following will insert two new ltdivgts and an exist ing ltdivgt as the last threechild nodes of the body
var $newdiv1 = $(ltdiv id=object1gt) newdiv2 = documentcreateElement(div) existingdiv1 = documentgetElementById(foo)
$(body)append($newdiv1 [newdiv2 existingdiv1])
Since append() can accept any number of addit ional arguments the same result can beachieved by passing in the three ltdivgts as three separate arguments like so
$(body)append($newdiv1 newdiv2 exist ingdiv1) The type and number of arguments willlargely depend on how you collect the elements in your code
Example 1 Appends some HTML to all paragraphs
Javascript
$(p)append(ltstronggtHelloltstronggt)
CSS
p backgroundyellow
HTML
ltpgtI would l ike to say ltpgt
Example 2 Appends an Element to all paragraphs
Javascript
$(p)append(documentcreateTextNode(Hello))
CSS
p backgroundyellow
HTML
ltpgtI would l ike to say ltpgt
Example 3 Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs
Javascript
$(p)append( $(strong) )
CSS
p backgroundyellow
HTML
ltstronggtHello worldltstronggtltpgtI would l ike to say ltpgt
val see Attributes
val see Attributes
text
Get the combined text contents of each element in the set of matched elements includingtheir descendants
Added in version 10
text()String
Unlike the html() method text() can be used in both XML and HTML documents The result ofthe text() method is a string containing the combined text of all matched elements (Due tovariat ions in the HTML parsers in dif ferent browsers the text returned may vary in newlines andother white space) Consider the following HTML
ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgt ltdivgt
The code $(divdemo-container)text() would produce the following result
Demonstrat ion Box list item 1 list item 2
The text() method cannot be used on form inputs or scripts To set or get the text value ofinput or textarea elements use the val() method To get the value of a script element use thehtml() method
As of jQuery 14 the text() method returns the value of text and CDATA nodes as well aselement nodes
Example 1 Find the text in the f irst paragraph (stripping out the html) then set the html of thelast paragraph to show it is just text (the red bold is gone)
Javascript
var str = $(pfirst)text() $(plast)html(str)
CSS
p colorblue margin8px b colorred
HTML
ltpgtltbgtTestltbgt Paragraphltpgt
ltpgtltpgt
text
Set the content of each element in the set of matched elements to the specif ied text
Added in version 14
text(funct ion(index text))jQuery
funct ion(indextext)Funct ion
A funct ion returning the text content to set Receives the indexposit ion of the element in the set and the old text value as arguments
Unlike the html() method text() can be used in both XML and HTML documents
We need to be aware that this method escapes the string provided as necessary so that it willrender correct ly in HTML To do so it calls the DOM method createTextNode() which replacesspecial characters with their HTML ent ity equivalents (such as amplt for lt) Consider the followingHTML
ltdiv class=demo-containergt ltdiv class=demo-boxgtDemonstration Boxltdivgt ltulgt ltligtlist item 1ltligt ltligtlist ltstronggtitemltstronggt 2ltligt ltulgtltdivgt
The code $(divdemo-container)text(ltpgtThis is a test ltpgt) will produce the following DOMoutput
ltdiv class=demo-containergtampltpampgtThis is a testampltpampgtltdivgt
It will appear on a rendered page as though the tags were exposed like this
ltpgtThis is a testltpgt
The text() method cannot be used on input elements For input f ield text use the val() method
As of jQuery 14 the text() method allows us to set the text content by passing in a funct ion
$(ul l i )text(function(index) return item number + (index + 1))
Given an unordered list with three ltligt elements this example will produce the following DOMoutput
ltulgt ltligtitem number 1ltligt ltligtitem number 2ltligt ltligtitem number 3ltligtltulgt
Example 1 Add text to the paragraph (not ice the bold tag is escaped)
Javascript
$(p)text(ltbgtSomeltbgt new text)
CSS
p colorblue margin8px
HTML
ltpgtTest Paragraphltpgt
html see Attributes
html see Attributes
toggleClass see Attributes
removeClass see Attributes
hasClass see Attributes
removeAttr see Attributes
attr see Attributes
attr see Attributes
addClass see Attributes
Data
jQueryhasData
Determine whether an element has any jQuery data associated with it
Added in version 15
jQueryhasData(element)Boolean
elementElement A DOM element to be checked for data
The jQueryhasData() method provides a way to determine if an element current ly has anyvalues that were set using jQuerydata() If no data is associated with an element (there is nodata object at all or the data object is empty) the method returns false otherwise it returnstrue
The primary advantage of jQueryhasData(element) is that it does not create and associate adata object with the element if none current ly exists In contrast jQuerydata(element) alwaysreturns a data object to the caller creat ing one if no data object previously existed
Example 1 Set data on an element and see the results of hasData
Javascript
$(function() var $p = jQuery(p) p = $p[0] $pappend(jQueryhasData(p)+ ) false jQuerydata(p testing 123) $pappend(jQueryhasData(p)+ ) true jQueryremoveData(p testing) $pappend(jQueryhasData(p)+ ) false )
HTML
ltpgtResults ltpgt
jQueryremoveData
Remove a previously-stored piece of data
Added in version 123
jQueryremoveData(element name)jQuery
elementElement A DOM element f rom which to remove data
nameString (opt ional) A string naming the piece of data to remove
Note This is a low-level method you should probably use removeData() instead
The jQueryremoveData() method allows us to remove values that were previously set usingjQuerydata() When called with the name of a key jQueryremoveData() deletes that part icularvalue when called with no arguments all values are removed
Example 1 Set a data store for 2 names then remove one of them
Javascript
var div = $(div)[0]$(spaneq(0))text( + $(div)data(test1))jQuerydata(div test1 VALUE-1)jQuerydata(div test2 VALUE-2)$(spaneq(1))text( + jQuerydata(div test1))jQueryremoveData(div test1)$(spaneq(2))text( + jQuerydata(div test1))$(spaneq(3))text( + jQuerydata(div test2))
CSS
div margin2px colorblue span colorred
HTML
ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt ltdivgtvalue2 after removal ltspangtltspangtltdivgt
jQuerydata
Store arbit rary data associated with the specif ied element Returns the value that was set
Added in version 123
jQuerydata(element key value)Object
elementElement The DOM element to associate with the data
keyString A string naming the piece of data to set
valueObject The new data value
Note This is a low-level method a more convenient data() is also available
The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f ree from memory leaks jQuery ensures that thedata is removed when DOM elements are removed via jQuery methods and when the userleaves the page We can set several dist inct values for a single element and retrieve them later
jQuerydata(documentbody foo 52)jQuerydata(documentbody bar test)
Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies
Example 1 Store then retrieve a value from the div element
Javascript
var div = $(div)[0] jQuerydata(div test first 16 last pizza ) $(spanfirst)text(jQuerydata(div test)first) $(spanlast)text(jQuerydata(div test)last)
CSS
div colorblue span colorred
HTML
ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt
jQuerydata
Returns value at named data store for the element as set by jQuerydata(element namevalue) or the full data store for the element
Added in version 14
jQuerydata(element)Object
elementElement The DOM element to query for the data
Note This is a low-level method a more convenient data() is also available
Regarding HTML5 data- at t ributes This low-level method does NOT retrieve the data-at t ributes unless the more convenient data() method has already retrieved them
The jQuerydata() method allows us to at tach data of any type to DOM elements in a way thatis safe f rom circular references and therefore f rom memory leaks We can retrieve severaldist inct values for a single element one at a t ime or as a set
alert(jQuerydata( documentbody foo ))alert(jQuerydata( documentbody ))
The above lines alert the data values that were set on the body element If nothing was set onthat element an empty string is returned
Calling jQuerydata(element) retrieves all of the element s associated values as a JavaScriptobject Note that jQuery itself uses this method to store data for internal use such as eventhandlers so do not assume that it contains only data that your own code has stored
Note this method current ly does not provide cross-plat form support for set t ing data on XMLdocuments as Internet Explorer does not allow data to be at tached via expando propert ies
Example 1 Get the data named blah stored at for an element
Javascript
$(button)cl ick(function(e) var value div = $(div)[0]
switch ($(button)index(this)) case 0 value = jQuerydata(div blah) break case 1 jQuerydata(div blah hello) value = Stored break case 2 jQuerydata(div blah 86) value = Stored break case 3 jQueryremoveData(div blah) value = Removed break
$(span)text( + value))
CSS
div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred
HTML
ltdivgtA divltdivgtltbuttongtGet blah from the divltbuttongtltbuttongtSet blah to helloltbuttongt
ltbuttongtSet blah to 86ltbuttongtltbuttongtRemove blah from the divltbuttongtltpgtThe blah value of this div is ltspangtltspangtltpgt
jQuerydequeue
Execute the next funct ion on the queue for the matched element
Added in version 13
jQuerydequeue(element queueName)jQuery
elementElement A DOM element f rom which to remove and execute a queuedfunct ion
queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue
Note This is a low-level method you should probably use dequeue() instead
When jQuerydequeue() is called the next funct ion on the queue is removed from the queueand then executed This funct ion should in turn (direct ly or indirect ly) cause jQuerydequeue() tobe called so that the sequence can cont inue
Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing
Javascript
$(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $dequeue( this ) ) $(div)animate(left10px top30px 700) )
CSS
div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred
HTML
ltbuttongtStartltbuttongt ltdivgtltdivgt
jQueryqueue
Show the queue of funct ions to be executed on the matched element
Added in version 13
jQueryqueue(element queueName)Array
elementElement A DOM element to inspect for an at tached queue
queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue
Note This is a low-level method you should probably use queue() instead
Example 1 Show the length of the queue
Javascript
$(show)cl ick(function () var n = jQueryqueue( $(div)[0] fx ) $(span)text(Queue length is + nlength) ) function runIt() $(div)show(slow) $(div)animate(left+=2002000) $(div)sl ideToggle(1000) $(div)sl ideToggle(fast) $(div)animate(left-=2001500) $(div)hide(slow) $(div)show(1200) $(div)sl ideUp(normal runIt) runIt()
CSS
div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue span colorred
HTML
ltbutton id=showgtShow Length of Queueltbuttongt ltspangtltspangt ltdivgtltdivgt
jQueryqueue
Manipulate the queue of funct ions to be executed on the matched element
Added in version 13
jQueryqueue(element queueName callback())jQuery
elementElement A DOM element on which to add a queued funct ion
queueNameString A string containing the name of the queue Defaults to fx thestandard ef fects queue
callback()Funct ion The new funct ion to add to the queue
Note This is a low-level method you should probably use queue() instead
Every element can have one or more queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion
The jQueryqueue() method allows us to direct ly manipulate this queue of funct ions CallingjQueryqueue() with a callback is part icularly useful it allows us to place a new funct ion at theend of the queue
Note that when adding a funct ion with jQueryqueue() we should ensure that jQuerydequeue()is eventually called so that the next funct ion in line executes
Example 1 Queue a custom funct ion
Javascript
$(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=200500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() )
CSS
div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue
HTML
Click here ltdivgtltdivgt
Example 2 Set a queue array to delete the queue
Javascript
$(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) jQueryqueue( $(div)[0] fx function () $(this)addClass(newcolor) jQuerydequeue( this ) ) $(div)animate(left-=2001500) jQueryqueue( $(div)[0] fx function () $(this)removeClass(newcolor) jQuerydequeue( this ) ) $(div)sl ideUp() ) $(stop)cl ick(function () jQueryqueue( $(div)[0] fx [] ) $(div)stop() )
CSS
div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue
HTML
ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt
clearQueue
Remove from the queue all items that have not yet been run
Added in version 14
clearQueue(queueName)jQuery
queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue
When the clearQueue() method is called all funct ions on the queue that have not beenexecuted are removed from the queue When used without an argument clearQueue()removes the remaining funct ions from fx the standard ef fects queue In this way it is similar tostop(true) However while the stop() method is meant to be used only with animat ionsclearQueue() can also be used to remove any funct ion that has been added to a genericjQuery queue with the queue() method
Example 1 Empty the queue
Javascript
$(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp())$(stop)cl ick(function () $(div)clearQueue() $(div)stop())
CSS
div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue
HTML
ltbutton id=startgtStartltbuttongtltbutton id=stopgtStopltbuttongtltdivgtltdivgt
removeData
Remove a previously-stored piece of data
Added in version 123
removeData(name)jQuery
nameString (opt ional) A string naming the piece of data to delete
The removeData() method allows us to remove values that were previously set using data()When called with the name of a key removeData() deletes that part icular value when calledwith no arguments all values are removed
NOTE Start ing with jQuery 143 calling removeData() will cause the value of the propertybeing removed to revert to the value of the data at t ribute of the same name in the DOM ratherthan being set to undef ined
Example 1 Set a data store for 2 names then remove one of them
Javascript
$(spaneq(0))text( + $(div)data(test1)) $(div)data(test1 VALUE-1) $(div)data(test2 VALUE-2) $(spaneq(1))text( + $(div)data(test1)) $(div)removeData(test1) $(spaneq(2))text( + $(div)data(test1)) $(spaneq(3))text( + $(div)data(test2))
CSS
div margin2px colorblue span colorred
HTML
ltdivgtvalue1 before creation ltspangtltspangtltdivgt ltdivgtvalue1 after creation ltspangtltspangtltdivgt ltdivgtvalue1 after removal ltspangtltspangtltdivgt
ltdivgtvalue2 after removal ltspangtltspangtltdivgt
data
Store arbit rary data associated with the matched elements
Added in version 143
data(obj)jQuery
objObject An object of key-value pairs of data to update
The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks
We can set several dist inct values for a single element and retrieve them later
$(body)data(foo 52)$(body)data(bar myType test count 40 )
$(body)data(foo) 52$(body)data() foo 52 bar myType test count 40
In jQuery 143 sett ing an element s data object with data(obj) extends the data previouslystored with that element jQuery itself uses the data() method to save informat ion under thenames events and handle and also reserves any data name start ing with an underscore (_)for internal use
Prior to jQuery 143 (start ing in jQuery 14) the data() method completely replaced all datainstead of just extending the data object If you are using third-party plugins it may not beadvisable to completely replace the element s data object since plugins may have also setdata
Due to the way browsers interact with plugins and external code the data() method cannot beused on ltobjectgt (unless it s a Flash plugin) ltappletgt or ltembedgt elements
Example 1 Store then retrieve a value from the div element
Javascript
$(div)data(test first 16 last pizza )$(spanfirst)text($(div)data(test)first)$(spanlast)text($(div)data(test)last)
CSS
div colorblue span colorred
HTML
ltdivgt The values stored were ltspangtltspangt and ltspangtltspangt ltdivgt
data
Returns value at named data store for the f irst element in the jQuery collect ion as set bydata(name value)
Added in version 14
data()Object
The data() method allows us to at tach data of any type to DOM elements in a way that is safefrom circular references and therefore f rom memory leaks We can retrieve several dist inctvalues for a single element one at a t ime or as a set
alert($(body)data(foo))alert($(body)data())
The above lines alert the data values that were set on the body element If no data at all wasset on that element undef ined is returned
alert( $(body)data(foo)) undefined$(body)data(bar foobar)alert( $(body)data(foobar)) foobar
HTML 5 data- Attributes
As of jQuery 143 HTML 5 data- at t ributes will be automat ically pulled in to jQuerys data object The treatment of at t ributes with embedded dashes was changed in jQuery 16 to conform tothe W3C HTML5 specif icat ion
For example given the following HTML
ltdiv data-role=page data-last-value=43 data-hidden=true data-options=nameJohngtltdivgt
All of the following jQuery code will work
$(div)data(role) === page$(div)data(lastValue) === 43$(div)data(hidden) === true$(div)data(options)name === John
Every at tempt is made to convert the string to a JavaScript value (this includes booleansnumbers objects arrays and null) otherwise it is lef t as a string To retrieve the valuesat t ribute as a string without any at tempt to convert it use the at t r() method When the dataattribute is an object (starts with ) or array (starts with [) then jQueryparseJSON is used toparse the string it must follow valid JSON syntax including quoted property names The data-at t ributes are pulled in the f irst t ime the data property is accessed and then are no longeraccessed or mutated (all data values are then stored internally in jQuery)
Calling data() with no parameters retrieves all of the values as a JavaScript object This objectcan be safely cached in a variable as long as a new object is not set with data(obj) Using theobject direct ly to get or set values is faster than making individual calls to data() to get or seteach value
var mydata = $(mydiv)data()if ( mydatacount lt 9 ) mydatacount = 43 mydatastatus = embiggened
Example 1 Get the data named blah stored at for an element
Javascript
$(button)cl ick(function(e) var value
switch ($(button)index(this)) case 0 value = $(div)data(blah) break case 1 $(div)data(blah hello) value = Stored break case 2 $(div)data(blah 86) value = Stored break case 3 $(div)removeData(blah) value = Removed break
$(span)text( + value))
CSS
div margin5px backgroundyellow button margin5px font-size14px p margin5px colorblue span colorred
HTML
ltdivgtA divltdivgt ltbuttongtGet blah from the divltbuttongt ltbuttongtSet blah to helloltbuttongt
ltbuttongtSet blah to 86ltbuttongt ltbuttongtRemove blah from the divltbuttongt ltpgtThe blah value of this div is ltspangtltspangtltpgt
dequeue
Execute the next funct ion on the queue for the matched elements
Added in version 12
dequeue(queueName)jQuery
queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue
When dequeue() is called the next funct ion on the queue is removed from the queue and thenexecuted This funct ion should in turn (direct ly or indirect ly) cause dequeue() to be called sothat the sequence can cont inue
Example 1 Use dequeue to end a custom queue funct ion which allows the queue to keepgoing
Javascript
$(button)cl ick(function () $(div)animate(left+=200px 2000) $(div)animate(top0px 600) $(div)queue(function () $(this)toggleClass(red) $(this)dequeue() ) $(div)animate(left10px top30px 700))
CSS
div margin3px width50px positionabsolute height50px left10px top30px background-coloryellow divred background-colorred
HTML
ltbuttongtStartltbuttongt ltdivgtltdivgt
queue
Show the queue of funct ions to be executed on the matched elements
Added in version 12
queue(queueName)Array
queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue
Example 1 Show the length of the queue
Javascript
var div = $(div)
function runIt() divshow(slow) divanimate(left+=2002000) divsl ideToggle(1000) divsl ideToggle(fast) divanimate(left-=2001500) divhide(slow) divshow(1200) divsl ideUp(normal runIt)
function showIt() var n = divqueue(fx) $(span)text( nlength ) setTimeout(showIt 100)
runIt()showIt()
CSS
div margin3px width40px height40px positionabsolute left0px top60px backgroundgreen displaynone divnewcolor backgroundblue p colorred
HTML
ltpgtThe queue length is ltspangtltspangtltpgt ltdivgtltdivgt
queue
Manipulate the queue of funct ions to be executed on the matched elements
Added in version 12
queue(queueName callback( next ))jQuery
queueNameString (opt ional) A string containing the name of the queue Defaults to fxthe standard ef fects queue
callback( next)Funct ion
The new funct ion to add to the queue with a funct ion to call thatwill dequeue the next item
Every element can have one to many queues of funct ions at tached to it by jQuery In mostapplicat ions only one queue (called fx) is used Queues allow a sequence of act ions to becalled on an element asynchronously without halt ing program execut ion The typical exampleof this is calling mult iple animat ion methods on an element For example
$(foo)sl ideUp()fadeIn()
When this statement is executed the element begins its sliding animat ion immediately but thefading transit ion is placed on the fx queue to be called only once the sliding transit ion iscomplete
The queue() method allows us to direct ly manipulate this queue of funct ions Calling queue()with a callback is part icularly useful it allows us to place a new funct ion at the end of thequeue
This feature is similar to providing a callback funct ion with an animat ion method but does notrequire the callback to be given at the t ime the animat ion is performed
$(foo)sl ideUp()$(foo)queue(function() alert(Animation complete) $(this)dequeue())
This is equivalent to
$(foo)sl ideUp(function() alert(Animation complete))
Note that when adding a funct ion with queue() we should ensure that dequeue() is eventuallycalled so that the next funct ion in line executes
In jQuery 14 the funct ion that s called is passed in another funct ion as the f irst argument thatwhen called automat ically dequeues the next item and keeps the queue moving You would useit like so
$(test)queue(function(next) Do some stuff next())
Example 1 Queue a custom funct ion
Javascript
$(documentbody)cl ick(function () $(div)show(slow) $(div)animate(left+=2002000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=200500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() )
CSS
div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue
HTML
Click here ltdivgtltdivgt
Example 2 Set a queue array to delete the queue
Javascript
$(start)cl ick(function () $(div)show(slow) $(div)animate(left+=2005000) $(div)queue(function () $(this)addClass(newcolor) $(this)dequeue() ) $(div)animate(left-=2001500) $(div)queue(function () $(this)removeClass(newcolor) $(this)dequeue() ) $(div)sl ideUp() ) $(stop)cl ick(function () $(div)queue(fx []) $(div)stop() )
CSS
div margin3px width40px height40px positionabsolute left0px top30px backgroundgreen displaynone divnewcolor backgroundblue
HTML
ltbutton id=startgtStartltbuttongt ltbutton id=stopgtStopltbuttongt ltdivgtltdivgt
Forms
submit
Bind an event handler to the submit JavaScript event or t rigger that event on an element
Added in version 10
submit()jQuery
This method is a shortcut for bind(submit handler) in the f irst variat ion and t rigger(submit ) inthe third
The submit event is sent to an element when the user is at tempt ing to submit a form It canonly be at tached to ltformgt elements Forms can be submit ted either by clicking an explicitltinput type=submitgt ltinput type=imagegt or ltbutton type=submitgt or by pressing
Enter when certain form elements have focus
Depending on the browser the Enter key may only cause a form submission if theform has exactly one text field or only when there is a submit button present Theinterface should not rely on a particular behavior for this key unless the issue isforced by observing the keypress event for presses of the Enter key
For example consider the HTML
ltform id=target action=destinationhtmlgt ltinput type=text value=Hello there gt ltinput type=submit value=Go gtltformgtltdiv id=othergt Trigger the handlerltdivgt
The event handler can be bound to the form
$(target)submit(function() alert(Handler for submit() called) return false)
Now when the form is submit ted the message is alerted This happens prior to the actualsubmission so we can cancel the submit act ion by calling preventDefault () on the event objector by returning false f rom our handler We can trigger the event manually when another elementis clicked
$(other)cl ick(function() $(target)submit())
After this code executes clicks on Trigger the handler will also display the message In addit ionthe default submit act ion on the form will be f ired so the form will be submit ted
The JavaScript submit event does not bubble in Internet Explorer However scripts that rely onevent delegat ion with the submit event will work consistent ly across browsers as of jQuery 14which has normalized the event s behavior
Example 1 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry
Javascript
$(form)submit(function() i f ($(inputfirst)val() == correct) $(span)text(Validated)show() return true $(span)text(Not valid)show()fadeOut(1000) return false )
CSS
p margin0 colorblue divp margin-left10px span colorred
HTML
ltpgtType correct to validateltpgt ltform action=javascriptalert(success)gt ltdivgt ltinput type=text gt
ltinput type=submit gt ltdivgt ltformgt ltspangtltspangt
Example 2 If youd like to prevent forms from being submit ted unless a f lag variable is set t ry
Javascript
$(form)submit( function () return thissome_flag_variable )
Example 3 To trigger the submit event on the f irst form on the page t ry
Javascript
$(formfirst)submit()
select
Bind an event handler to the select JavaScript event or t rigger that event on an element
Added in version 10
select()jQuery
This method is a shortcut for bind(select handler) in the f irst two variat ions andtrigger(select ) in the third
The select event is sent to an element when the user makes a text select ion inside it Thisevent is limited to ltinput type=textgt f ields and lttextareagt boxes
For example consider the HTML
ltformgt ltinput id=target type=text value=Hello there gtltformgtltdiv id=othergt Trigger the handlerltdivgt
The event handler can be bound to the text input
$(target)select(function() alert(Handler for select() called))
Now when any port ion of the text is selected the alert is displayed Merely set t ing the locat ionof the insert ion point will not t rigger the event To trigger the event manually apply select()without an argument
$(other)cl ick(function() $(target)select())
After this code executes clicks on the Trigger button will also alert the message
Handler for select() called
In addit ion the default select act ion on the f ield will be f ired so the ent ire text f ield will beselected
The method for retrieving the current selected text differs from one browser toanother A number of jQuery plug-ins offer cross-platform solutions
Example 1 To do something when text in input boxes is selected