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
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)) )
Get the value of a property for the f irst element in the set of matched elements
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
Javascript
$(input)select( function () $(div)text(Something was selected)show()fadeOut(1000) )
CSS
p colorblue div colorred
HTML
ltpgt
Click and drag the mouse to select text in the inputs ltpgt ltinput type=text value=Some text gt ltinput type=text value=to test on gt
ltdivgtltdivgt
Example 2 To trigger the select event on all input elements t ry
Javascript
$(input)select()
change
Bind an event handler to the change JavaScript event or t rigger that event on an element
Added in version 10
change()jQuery
This method is a shortcut for bind(change handler) in the f irst two variat ions andtrigger(change) in the third
The change event is sent to an element when its value changes This event is limited to ltinputgtelements lttextareagt boxes and ltselectgt elements For select boxes checkboxes and radiobuttons the event is f ired immediately when the user makes a select ion with the mouse butfor the other element types the event is deferred unt il the element loses focus
For example consider the HTML