Sunteți pe pagina 1din 9

Tutorial2CSSSelectorsWalkthrough

WrittenbyGregSidelnikov

Whowantstobefriends? MyTwitterMyFacebookaboutme

SubscribetomyFreejQueryTutorialNewsletter
Free,booklikequalitycontentforselfeducation. ReceiveuniquejQuerytipsandjQuerytutorialsforbeginners fromGreg,theauthorofthisarticleandvariousjQueryPlugins.

Email:

Subscribe

Youremailaddressis100%spamsafewithme.
AllEpisodesare100%Free
Episode1PluginDevelopmentExplained Episode2CSSSelectorswith visualcheatsheetdiagrams Episode3jQueryEvents Episode4 HowtospeedupyourjQuerycode Episode5MakeHTTPrequestswithAjaxandjQuery Episode6DealingWithInputFields Episode7jQueryAnimation Episode8DevelopingaTouchscreenUserInterfacewithSound Episode9CapturingKeyboardEvents Episode10MakingajQueryGame:Tetris Episode11CreateanAutosuggestInputField(PHP&MySQL) Episode12UsingSelectorstoTraverseComplexHTML

Subscriber'sRights: Youcanshareeachindividualepisodewithfriendsasyoureceivethem.

TABLEOFCONTENTSInThisEdition:
Whatkindofelementscanyouselect? Figure1:BasicCSSSelectors(image) Figure2:UnderstandingDOMStructure(image) CommonCSSSelectorexamples CSSSelectorReferenceTable Thepowerofthecolon Iselectedanelement,what'snext? Makingcomplexselectionselegant

AbouttheAuthor MynameisGreg,IamanexperiencedjQuery developerwhosimplywishestosharehisknowledge withothers.Becausethisnewsletteristargetedat beginners,whichisprobablythetypeofpeoplewho canbenefitfromtutorials,Itrytogoindetailwhen describingcertainaspectsofjQuerydevelopment. Makeasuggestion,correctanerror,oraskmea jQueryrelatedquestiononFacebook: MyFacebook MyTwitter aboutme

MynameisGreg,asyoumayalreadyknow.IamtheauthorofnumerousjQuery tutorialsandpublications.Yourcontinuedreadershipismuchappreciatedand keepsmemotivatedtowritemorejQuerytutorials. ThisnewsletterissueisaboutCSSSelectors,theimportanceofknowingwhat DOMisandlearningtoselectelementsofallkindsindifferentways. CSSselectorsplaycrucialpartinjQuerydevelopment.Manypeopleare comfortablewithjustlearningafew,neverreallyreachingthepotentialofusing themincombinationswithjQueryfunctionsthatfurtherenableustomakecomplex selections. Youwanttolearnasmanyselectorsaspossibleifyouwanttoincreaseyour productivity.Butdon'tlearnthemallatonce.Experimentwithoneselectoratatime, andbuildyourknowledgeonyourpastexperience. Let'sconsidersomeoftheverybasicjQueryselectors:

Thefirsttwoexamplesareprettystraightforward.Youmayhavealreadyexperimentedwiththesemethods.

Get upto 16 GBs free online storage access your documents anywhere!
dropbox.com

Free Online Storage

ThethirdexamplesshowshowwecanselectBODYbyreferringtoitasparentofDIVitcontains.TheDIV,inthisinstanceisreferredtoasa childofBODY. Thefunctionparent()ispartofasetoffunctionsfortraversingyourDocumentObjectModelcreatedbynestingHTMLtagswithinone another. Otherelementtraversingfunctionsexist,suchasnext()andprevious().Italkmoreaboutthembelow,butfirstweneedtounderstandhow elementsareselected.CSSSelectorsoperateexclusivelyontheDOMstructure.

Whatkindofelementscanyouselect?
jQueryselectorscanselectprettymuchanyHTMLelement.AndifyouunderstandthebasicsofDOM(DocumentObjectModel),youareata greatadvantage.UsingyourknowledgeofDOMandjQueryselectorstogethercansignificantlyreducethetimeyouspenddeveloping dynamicJavascriptcode. HereisthebasicideaofwhatDOMlookslike.TheHTMLequivalentofthisDOMstructureisdisplayedintheupperleftcorner.

TheDOMisprettyeasytounderstand.ItisveryusefulforthinkingaboutyourjQueryselectors.Butit'ssurprisinghowmanypeopleignoreit. RespecttheDOM.Don'tignoreit.
Instant-Installation, Compact size. designed and manufactured in Taiwan
www.josn.com.tw

Tyredog TPMS

CSSSelectorcodeisthefirstparameterofthemainjQueryobject.Let'squicklytakealookatthedefinitionagain: jurucinslco,cnet*Lbaycd/} Qey=fnto(eetrotx){/irroe* TheselectorargumentisoneofthemostfrequentlyusedparametersofjQuery.Manypeopledon'tevenrealizethatthereisasecond argumentthattheycanpass,calledcontext.I'llgetbacktothatlaterinthistutorial. TheselectorparameterspecifiestheCSSselectorcode.Oncetheelementinquestionisselected,wecanrunafunctiononit. jur(dv)hd( Qey'i'.ie) ThiswillselectallDIVelementswithintheBODYbranchoftheDOM. Ifmultipleelementshavebeenselected,thisfunctionwillrunonallselectedelements.Thismeans,itwillhideallDIVelementsinBODY,even thoughBODYisnotevenapartofthedefinition.ItisassumedthatthefirstselectorreferstotheBODYbranchinDOM.Wecanexplicitly specifyBODYinourselector,asyouwillseeintheexamplesbelowforthesakeofbeingcomplete.Butitisnotalwaysnecessary.

CommonCSSSelectorExamples
Let'stakealookatsomeofthemostcommonjQueryselectorsthatyouareprobablygoingtobeusingallthetime. Probablyoneofthemostcommonselectorsisthe#symbol.ItstandsforselectingaDIVwithanIDspecifiedimmediatelyafterthe#symbol. /eetalmnhthsIf"o"niei /SlcneeettaaDodg,adhdt jur(#o'.ie) Qey'dg)hd( /eetDVeeettaaDoo,adhdt /SlcIlmnhthsIfdgniei jur(dvdg)hd( Qey'i#o'.ie) WecanalwaysrefertoanelementwithanIDof"dog"as#doginourjQueryselector.IfwewanttobespecificandselectaDIVwithanIDof "dog",wecanuse"div#dog".Ofcourse,thisisamatterofsemantics.Followingtherulethattherecould(orshould)beonlyoneelementwith auniqueIDperwebpage,itprobablymakesnosenseprefixingtheselectorsthatstartwith#withthenameofanelement. TotraversetheDOMandmakesurethatweareselectingtherightthing,wecanusetheSPACE()operator.ThespaceoperatorletsDOM knowexactlywhichbranchwewanttotraverse: /iealDVnieBD,btntBDtef /HdlIsisdOYuoOYisl jur(bdi'.ie) Qey'oydv)hd( /iealDVniefrtDVcidoOYuoIhltef /HdlIsisdisIhlfBD,btntDVcidisl jur(bdii'.ie) Qey'oydvdv)hd( /iealDVniefrtDVcidoOYwoeis#ert /HdlIsisdisIhlfBDhsdisce jur(bdi#ertdv)hd( Qey'oydvscei'.ie) Notethatnoneoftheelementsbeforethelastspaceareactuallyselected.Onlythelastoneis.Thevaluesbeforethelastspacesimply indicatetheDOMpathtotraverse,butthepathitselfisnotselected,onlythelastelementinthepath.

CSSSelectorReference
ThefollowingdiagramsvisuallyexplainhowmanyjQueryCSSselectorswork.Printitout,youmayfinditasausefulreferencetokeepon yourdesk.

Forsimplicity'ssake,IusedonlyDIVelementstotestthefunctionalityoftheselectorsshownabove.

The Most Recognised & Comprehensive Multimedia Technology Event in Asia


broadcast-asia.com/Register_Now

BroadcastAsia 2012 S'pore

ThereareafewmoreselectorsIleftoutfromthattable.Noticethatthistableusesspacesandcolons.Insomecases,thereisaspace beforeacolon,inothercasesthereisn't.

Thepowerofthecolon
InthissectionIwanttoexplorethecolon(:)injQueryselectors.Thecolonislikeaminihelpertoolthatletsusconvergetotheelementwe aresearchingforwithgreaterprecision. BelowIlistmostofthecasesingeneralwhenthecolonisused:

Selector :first :last :even :odd :eq(index) :gt(N) :lt(N) :not(selector) :header

RealworldSituation $("p:first") $("p:last") $("tr:even") $("tr:odd") $("ulli:eq(3)") $("ulli:gt(3)") $("ulli:lt(3)") $("input:not(:empty)") $(":header")

Description Thefirstpelement Thelastpelement Alleventrelements Alloddtrelements Thefourthelementinalist(indexstartsat0) Listelementswithanindexgreaterthan3 Listelementswithanindexlessthan3 Allinputelementsthatarenotempty Allheaderelementsh1,h2...

:animated $(":animated") Allanimatedelements :contains(text) $(":contains('clockworkorange')") Allelementscontainingtext'clockworkorange' :empty $(":empty") Allelementswithnochild(elements)nodes :hidden $("p:hidden") Allhiddenpelements :visible $("table:visible") Allvisibletables

Forthefulllist,visittheofficialjQuerydocumentation:here ButcolonisalsowidelyusedwithINPUTelements.Inmanycases,forexample,whendealingwithradiobuttons,checkboxesortextareas, someoftherulesthatapplytoblockingelements(suchasDIV)donotapply.Thenumberofthecolonbasedselectorscanoverwhelm someonewhoisjuststartingtolearnjQuery.Iwouldn'twantthattohappentomyreaders.ButI'llgettotheotheronesaswell,aswemove forward. Infact,Icreatedacompletelyseparatenewsletterepisodetoaddresstheissueofcolonselectorsforinputelements.Usingthecolontowork withinputelementswillbediscussedinanupcomingnewsletterepisodecalledDealingWithInputElements.Thecontentwillincludetype= "text"inputboxes,textareas,checkboxes,radiobuttonsandothers.Fornow,let'sseewhatwecandowithelementsafterwehaveselected them.

Iselectedanelement,what'snext?
SometimeswewanttoworkwiththethisobjectwhichreferstotheobjectthatyourJavascriptapplicationcurrentlyhasfocuson,duringthe executionflowofyourscript.HereisabasicinlineCSSexampleofthethiskeywordinaction: <id="rsnlcti.tl.akrud='od"Ii<dv dviii"ocik="hssyebcgongl'>rs/i>

ClickingonthisDIVwillturnitsbackgroundtogoldcolor. WecanachievethesameexacteffectbyrewritingitforjQueryuse,likethis: <id="rsnlc$ti)cs'akrud,'od)"Ii<dv dviii"ocik="(hs.s(bcgon'gl'>rs/i> Whenreferringtoitself,wedonotusequotesaroundtheselector.Simplyusethisastheselector,withoutquotes. BecausetheDIVelementhasIDof"iris",thesameexacteffectcouldbeachievedbydoingsomethinglike:

$"ii".s(bcgon'gl' (#rs)cs'akrud,'od)

Inthiscase,cssisthefunctionwewanttoapplytoselectedelements.Whateverwasselected,willnowbeliableforreceivingtheeffect causedbythefunctionappliedtotheselection.Becauseinthisinstanceweusethecssfunction,whichispartofthestandardjQuerylibrary, theDIVelement'sbackgroundcolorwillturntogold. jQueryoffersalargenumberoffunctionsthatcanbeappliedtotheelementsyouhaveselected.Youcanhideelements,changetheirCSS propertiesasintheexampleabove,andyoucanattacheventstoelementssuchasonclickoronmouseover. Let'stakealookatsomeofthesefunctionsnow.

Function css(style, value) hide() show() prev() next() parent() html() text() animate()

UsageExample css('background','#ff0000') $('div').hide() $('div').show() $('div').prev() $('div').next() $('div').parent() $('div').html('<p>new</p>') $('div').text('newtext') $('div').animate({backgroundColor:"#ff0000"}, 1000)

Description ApplyaCSSstyletoanelement HideallDIVelementsonthepage(display:none) ShowallDIVelementsonthepage(display:block) Gotopreviouschild,placedsidebysideincurrent parent Gotonextchildwithinthecurrentparent Gototheparentofthecurrentlyselectedelement ReplacetheactualHTMLcontentofanelement Replacethetextwithinanelement Animatebackgroundcolortoredin1second

Thistablelistsonlysomeofthefunctions.ItriedtochoosesomeofthemoreimportantonesthatIuseoften.Therearemanymorefunctions relatedtoeachspecificgroupoftasks:events,CSS,visualeffects,animation,ajaxandutilities.Dumpingtableswithlargeamountsof functionsisnotmystyleofwritingahelpfultutorial. Iusuallyliketoexplainfunctionsindetailinthecontextofmytutorialsaswemovealongfromonesubjecttoanother.ThiswayIhavea chanceofshowingexamplesofpracticalusesofthesefunctions.Fornowtrytoexperimentwiththefunctionsfromthetableaboveinyour ownprojects. Asyoufollowmyfuturenewsletterepisodes,youwillgainadeeperunderstandingofusingCSSSelectors.Iusepracticalexamplesallthe time.

Makingcomplexselectionselegant
IwanttoconcludethisepisodebyshowingyouanexampleofacomplexCSSselection. TheideacamefromarealprojectIamworkingonwhereIwantedtoupdateatablecell,basedonwhetheranytextlocatedinaninputfield inanadjacenttablecellhasjustbeenchanged.Iwantedtotriggerthiswhentheinputfieldinquestionlostfocus. Thiswouldthenchangethetextinanadjacenttablecellfromoktoch,anindicatorthat"thevaluehasbeenchangedforthiselement".This waylaterIcouldsimplygrab(again,usingjQuery)onlyinputfieldsthathavebeenchangedtonewvaluesandsendittothescripttoupdate them,whileignoringvaluesthatwereunchanged. Thisexamplewillalsoshowyouhowtoattachaneventtoatextinputbox,insteadofaddingonblurdirectlyintotheinputfieldbywriting HTMLcode.ThoseattributebasedHTMLeventssuchasonmouseoveroronmouseoutonlycluttertheHTMLcode.

<ed ha> <cittp=tx/aacit> srpye"etjvsrp" $dcmn)rayfnto( (ouet.ed(ucin) { (tbet:thl()ipt)cag(ucin) $'aldnhcid3nu'.hnefnto( { (hs.aet)pe(.tl'h) $ti)prn(.rv)hm(c' ) } } ) <srp> /cit <ha> /ed <al> tbe <r<dIe<t><dSau<t><dIpt/d<t> t>t>tm/dt>tts/dt>nu<t>/r <r<dFrtNm<t><do<t><d<nuye="et/<t>/r t>t>isae/dt>k/dt>ipttptx">/d<t> <r<dLsae/d<do<t><d<nuye="et/<t>/r t>t>atNm<t>t>k/dt>ipttptx">/d<t> <r<dBrha<t><do<t><d<nuye="et/<t>/r t>t>itdy/dt>k/dt>ipttptx">/d<t> <r<dLcto<t><do<t><d<nuye="et/<t>/r t>t>oain/dt>k/dt>ipttptx">/d<t> <r<dOcpto<t><do<t><d<nuye="et/<t>/r t>t>cuain/dt>k/dt>ipttptx">/d<t>

<tbe /al>

Asmuchasthecodeabovewillspeaksforitself,Iwanttogiveyouabriefideaofwhatisgoingon.FirstweattachajQueryeventtoallinput boxesthatarelocatedin3rdcolumnofthetable.AllofthisispossibletodowiththejQueryselector'tabletd:nthchild(3)input'.Thisselector alonehasjustsavedusfromretypingtheseeventsintoindividualinputboxeswithinthetable,whichwouldbeamajorpain. Afterselectingalloftheseinputboxes,weattachthechangeeventtoit,andassignitafunction.Whatevergoesinsidethe{...}bracketsof thatfunctionwillexecuteeverytimetheinputfieldlosesfocus(whenyouclickoutofit,inotherwordsonblur). Notethatthenamelessfunctionclosureinsidethechange(...)eventwillactuallybeassignedtoeachindividualcellinthethirdcolumnofthis table,onebyone(thefunctionisassignedforeachtablecellinthe3rdcolumn).Thisiswhatthetabletd:nthchild(3)inputselectordoes.It goesintoeachcellofthethirdcolumnonebyone,usingeachcellasthestartingpoint. Let'sseewhatelseactuallyhappenshere: WeusethejQuery'sparent()function.TheparentoftheselectedinputboxistheTDcellinwhichitislocated. Wenowusetheprev()functiononparent,togobackoneTDcell.ThisisbecausethepreviouschildoftheTDinwhichtheinputboxisin,is the"status"TD.That'stheoneweneedtoupdate.Thismeanswearenowinthe"status"TDcell. Let'smodifythestatusTDcellwithanewmessage,becausetheinputhasbeenmodifiedforthatrow'sinputbox.Weusehtml('ch')function. ThedefaultHTMLinthestatuscellis"ok",andnowwechangeitto"ch"(for:ithasbeenchanged!),oralsoknownas"dirty"inthesoftware developercircles. Ofcourseyoucangetcreativeanddowhateveryouwant,changethecell'sbackgroundcolorbyusingcss('background','red'),oreveninsert acustomimageiconindicatinga"changed"state.ThepointisthatbyusingDOM'selementassociations,wewereabletotraversetheDOM treebackwardsandintotheelementweneededtoupdate.Andallwithoutusingspiderwebcode. IbelievethatthisexampleillustratedhowmuchmoresimpleyourJavascriptdevelopmentcanbeusingjQuery.Trytosticktosimilarideas presentedhere.Traversefieldsusingtheirchildrenandparents,insteadofdirectlyaccessingthembyID.Thiscanbeextremelypowerful techniqueandkeepsyourcodecleanandeasytoedit. YouhavereachedtheendofthistutorialIhopeyouenjoyedreadingitasmuchasIenjoyedwritingit.Haha,actually,writingthese newslettersisnoteasy,Ispendover9hoursoneach.ButItrulydohopeithelpssomeoneoutthere. ThepurposeofthisnewsletterepisodeistoshowyouhowtoeffectivelyusesomeCSSselectorstomakebasic,aswellascomplex selections.IfbytheendofreadingthisarticleyouhavebecomeafasterjQueryprogrammer,orlearnedsomethingnew,Ihavesucceeded. ThisconcludesourdiscussionofCSSselectors.

SupportmyjQueryTutorialwork Ow...yellowhurts.Italsohurtstowritegreattutorialssuchastheseforfree! ItmakesadifferencewhenyouClickHeretosubmitaPayPaldonationtokeepmycreativejuicesflowing. Averagedonationisabout$13,butyoucansubmitamonetarydonationintheamountofyourchoice.

Likethisepisode?Tellyourfriendsaboutitpleasesharethisnewsletterwithfriendsbyusinglinksbelow. TopasteinFacebook:

http://www.learnjquery.org/newsletter/Tutorial2jquerycssselectorswalkthrough.html
Topasteintoawebsiteasahyperlink:

<ahref='http://www.learnjquery.org/newsletter/Tutorial2jquerycssselectorswalkthrough.html'>jQueryCSSSelectorsTutorial</a>
Thanksforsharing!IreallyappreciatethisitreallymotivatesmetowriteevenmorefreejQuerytutorials. Seeyouinthenextepisode.

NextEpisodes:
Episode1jQueryPluginDevelopment Episode2jQueryCSSSelectors Episode3UnderstandingjQueryEvents<NextUp Episode4HowtospeedupjQuery Episode5jQueryandmakingHTTPrequestswithAjax Episode6DealingWithInputFields

Episode7jQueryAnimation Episode8DevelopingaTouchscreenUserInterfacewithSoundEffects Episode9CapturingKeyboardEvents Episode10MakingajQueryGame:Tetris Episode11CreateanAutosuggestInputField(PHP&MySQL) Episode12LongdistanceTravel:TraversingComplexHTML

RecommendedMaterial
UnderstandingjQueryismyjQuerybook jQueryPluginPatternforBeginnersMyfirstfulllengthjQueryPlugintutorial MonaLisaShufflePluginMyfirsteverjQueryplugin.

DiscussthistutorialwithyourFacebookAccount: Pleasepostcomments,errorcorrectionsorsuggestions:

2012WrittenandeditedbyGregSidelnikov.Errorcorrections?Suggestions?Emailme:greg.sidelnikov@gmail.com

S-ar putea să vă placă și