Description:AcceptsastringcontainingaCSSselectorwhichisthenusedtomatchasetofelements.
Inthefirstformulationlistedabove,jQuery()—whichcanalsobewrittenas$()—searchesthroughtheDOMforanyelementsthatmatchtheprovidedselectorandcreatesanewjQueryobjectthatreferencestheseelements:
Bydefault,selectorsperformtheirsearcheswithintheDOMstartingatthedocumentroot.However,analternatecontextcanbegivenforthesearchbyusingtheoptionalsecondparametertothe$()function.Forexample,todoasearchwithinaneventhandler,thesearchcanberestrictedlikeso:
$("div.foo").on("click",function(){$("span",this).addClass("bar");});Whenthesearchforthespanselectorisrestrictedtothecontextofthis,onlyspanswithintheclickedelementwillgettheadditionalclass.
Internally,selectorcontextisimplementedwiththe.find()method,so$("span",this)isequivalentto$(this).find("span").
ThesecondandthirdformulationsofthisfunctioncreateajQueryobjectusingoneormoreDOMelementsthatwerealreadyselectedinsomeotherway.AjQueryobjectiscreatedfromthearrayelementsintheordertheyappearedinthearray;unlikemostothermulti-elementjQueryoperations,theelementsarenotsortedinDOMorder.Elementswillbecopiedfromthearrayas-isandwon'tbeunwrappedifthey'realreadyjQuerycollections.
PleasenotethatalthoughyoucanpasstextnodesandcommentnodesintoajQuerycollectionthisway,mostoperationsdon'tsupportthem.ThefewthatdowillhaveanexplicitnoteontheirAPIdocumentationpage.
Acommonuseofsingle-DOM-elementconstructionistocalljQuerymethodsonanelementthathasbeenpassedtoacallbackfunctionthroughthekeywordthis:
$("div.foo").on("click",function(){$(this).slideUp();});Thisexamplecauseselementstobehiddenwithaslidinganimationwhenclicked.BecausethehandlerreceivestheclickediteminthethiskeywordasabareDOMelement,theelementmustbepassedtothe$()functionbeforeapplyingjQuerymethodstoit.
XMLdatareturnedfromanAjaxcallcanbepassedtothe$()functionsoindividualelementsoftheXMLstructurecanberetrievedusing.find()andotherDOMtraversalmethods.
$.post("url.xml",function(data){var$child=$(data).find("child");});CloningjQueryObjectsWhenajQueryobjectispassedtothe$()function,acloneoftheobjectiscreated.ThisnewjQueryobjectreferencesthesameDOMelementsastheinitialone.
Atpresent,theonlyoperationssupportedonplainJavaScriptobjectswrappedinjQueryare:.data(),.prop(),.on(),.off(),.trigger()and.triggerHandler().Theuseof.data()(oranymethodrequiring.data())onaplainobjectwillresultinanewpropertyontheobjectcalledjQuery{randomNumber}(eg.jQuery123456789).
//Defineaplainobjectvarfoo={foo:"bar",hello:"world"};//PassittothejQueryfunctionvar$foo=$(foo);//Testaccessingpropertyvaluesvartest1=$foo.prop("foo");//bar//Testsettingpropertyvalues$foo.prop("foo","foobar");vartest2=$foo.prop("foo");//foobar//Testusing.data()assummarizedabove$foo.data("keyName","someValue");console.log($foo);//willnowcontainajQuery{randomNumber}property//Testbindinganeventnameandtriggering$foo.on("eventName",function(){console.log("eventNamewascalled");});$foo.trigger("eventName");//Logs"eventNamewascalled"Should.trigger("eventName")beused,itwillsearchforan"eventName"propertyontheobjectandattempttoexecuteitafteranyattachedjQueryhandlersareexecuted.Itdoesnotcheckwhetherthepropertyisafunctionornot.Toavoidthisbehavior,.triggerHandler("eventName")shouldbeusedinstead.
$foo.triggerHandler("eventName");//Alsologs"eventNamewascalled"Examples:Findallpelementsthatarechildrenofadivelementandapplyabordertothem.
$("input:radio",document.forms[0]);FindalldivelementswithinanXMLdocumentfromanAjaxresponse.
$("div",xml.responseXML);Setthebackgroundcolorofthepagetoblack.
$(document.body).css("background","black");Hidealltheinputelementswithinaform.
Ifastringispassedastheparameterto$(),jQueryexaminesthestringtoseeifitlookslikeHTML(i.e.,itstartswith
Bydefault,elementsarecreatedwithan.ownerDocumentmatchingthedocumentintowhichthejQuerylibrarywasloaded.Elementsbeinginjectedintoadifferentdocumentshouldbecreatedusingthatdocument,e.g.,$("
helloiframe
",$("#myiframe").prop("contentWindow").document).IftheHTMLismorecomplexthanasingletagwithoutattributes,asitisintheaboveexample,theactualcreationoftheelementsishandledbythebrowser's.innerHTMLmechanism.Inmostcases,jQuerycreatesanew
WhenpassingincomplexHTML,somebrowsersmaynotgenerateaDOMthatexactlyreplicatestheHTMLsourceprovided.Asmentioned,jQueryusesthebrowser's.innerHTMLpropertytoparsethepassedHTMLandinsertitintothecurrentdocument.Duringthisprocess,somebrowsersfilteroutcertainelementssuchas,
Toensurecross-platformcompatibility,thesnippetmustbewell-formed.Tagsthatcancontainotherelementsshouldbepairedwithaclosingtag:
$("");$("");WhenpassingHTMLtojQuery(),notethattextnodesarenottreatedasDOMelements.Withtheexceptionofafewmethods(suchas.content()),theyaregenerallyignoredorremoved.E.g:
AsofjQuery1.8,anyjQueryinstancemethod(amethodofjQuery.fn)canbeusedasapropertyoftheobjectpassedtothesecondparameter:
$("
",{"class":"my-div",on:{touchstart:function(event){//Dosomething}}}).appendTo("body");Thename"class"mustbequotedintheobjectsinceitisaJavaScriptreservedword,and"className"cannotbeusedsinceitreferstotheDOMproperty,nottheattribute.Whilethesecondargumentisconvenient,itsflexibilitycanleadtounintendedconsequences(e.g.$("",{size:"4"})callingthe.size()methodinsteadofsettingthesizeattribute).Thepreviouscodeblockcouldthusbewritteninsteadas:
$("
").addClass("my-div").on({touchstart:function(event){//Dosomething}}).appendTo("body");Examples:Createadivelement(andallofitscontents)dynamicallyandappendittothebodyelement.Internally,anelementiscreatedanditsinnerHTMLpropertysettothegivenmarkup.$("
Hello
Thisfunctionbehavesjustlike$(document).ready(),inthatitshouldbeusedtowrapother$()operationsonyourpagethatdependontheDOMbeingready.Whilethisfunctionis,technically,chainable,therereallyisn'tmuchuseforchainingagainstit.
ExecutethefunctionwhentheDOMisreadytobeused.
$(function(){//Documentisready});Useboththeshortcutfor$(document).ready()andtheargumenttowritefailsafejQuerycodeusingthe$alias,withoutrelyingontheglobalalias.