CONTENTS INCLUDE: JQuery Selectors - Cheat Sheets

2y ago
14 Views
2 Downloads
2.12 MB
6 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Amalia Wilborn
Transcription

Get More Refcardz! Visit refcardz.com#7CONTENTS INCLUDE:nWhat are jQuery Selectors?nTypes of jQuery SelectorsnBasic CSS SelectorsnCustom jQuery SelectorsnMatched Set MethodsnHot Tips and more.jQuery SelectorsBy Bear Bibeault & Yehuda KatzBasic CSS SelectorsWHAT ARE JQUERY SELECTORS?These selectors follow standard CSS3 syntax and semantics.jQuery selectors are one of the most important aspects of thejQuery library. These selectors use familiar CSS syntax to allowpage authors to quickly and easily identify any set of pageelements to operate upon with the jQuery library methods.Understanding jQuery selectors is the key to using the jQuerylibrary most effectively. This reference card puts the power ofjQuery selectors at your very fingertips.A jQuery statement typically follows the syntax pattern:SyntaxDescription*Matches any element.EMatches all elements with tag name E.E FMatches all elements with tag name F that are descendants of E.E FMatches all elements with tag name F that are direct children of E.E FMatches all elements with tag name F that are immediatelypreceded by a sibling of tag name E.E FMatches all elements with tag name F that are precededby any sibling of tag name E.E:has(F)Matches all elements with tag name E that have at least onedescendant with tag name F.E.cMatches all elements E that possess a class name of c.Omitting E is identical to *.c.E#iMatches all elements E that possess an id value of i.Omitting E is identical to *#i.E[a]Matches all elements E that posses an attribute a of any value.E[a v]Matches all elements E that posses an attribute a whose value isexactly v.E[a v]Matches all elements E that posses an attribute a whose value startswith v.E[a v]Matches all elements E that posses an attribute a whose value endswith v.E[a* v]Matches all elements E that posses an attribute a whose valuecontains v. (selector).methodName();The selector is a string expression that identifies the set ofDOM elements that will be collected into a matched set to beoperated upon by the jQuery methods.www.dzone.comMany of the jQuery operations can also be chained: (selector).method1().method2().method3();As an example, let’s say that we want to hide the DOM elementwith the id value of goAway and to add class name incognito: pplying the methods is easy. Constructing the selectorexpressions is where the cleverness lies.HotTipThe wrapped set created by the application of aselector can be treated as a JavaScript array forconvenience. It is particularly useful to use arrayindexing to directly access elements within thewrapped set.Examplesnn (‘div’) selects all div elements (‘fieldset a’) selects all a elements within fieldset elements For example:var element (‘img’)[0];tech facts at your fingertipsjQuery Selectorswill set the variable element to the first elementin the matched set.Get More Refcardz(They’re free!)nnnTYPES OF JQUERY SELECTORSMethod Nameopen(method, url, async)onreadystatechangea URLopen a connection to(GET, POST, etc.)method HTTP verbinclude querystringurl url to open, mayasynchronous requestasync whether to onseHeaderThe Basic Selectors are known as “find selectors” as they are usedto find elements within the DOM. The Positional and CustomSelectors are “filter selectors” as they filter a set of elements(which defaults to the entire set of elements in the DOM).DZone, Inc.HotTipas callback (similar to onclick,assign a function objectevent model)onload, etc. in browsersetRequestHeader(namevalue)There are three categories of jQuery selectors: Basic CSSselectors, Positional selectors, and Custom jQuery selectors.nParameters and Descriptionsadd a header to the HTTPtech facts atrequestyour fingertipsnsend the requestas request bodybody string to be usedfor the responsestop the XHR from listening(only populated after send()stage in lifecycle of responseis called)after(integer, only populatedThe HTTP return codeloaded state)response reaches theset afterJavaScript string (onlybody of response as ainteractive readyState)response reaches the(onlyas a XML document objectbody of the responsethe interactive readyState)set after response reachesread a response headernby nameGet an array of all responseheader namesnAuthoritative contentDesigned for developersWritten by top expertsLatest tools & technologiesHot tips & examplesBonus content onlineNew issue every 1-2 weeksSubscribe Now for FREE!Refcardz.com www.dzone.com

2jQuery Selectorstech facts at your fingertipsBasic CSS Selectors, continuedPositional Selectors, continuedExamplesSyntaxDescriptionB:oddSelects the odd elements within the set of elements defined by B.B:eq(n)Selects the n-th element within the set of elements definedby B. Starts at 0.B:gt(n)Selects elements within the set of elements defined by Bthat follow the n-th element (exclusive). Starts at 0. (‘p:has(b)’) selects all p elements that contain a b elementB:lt(n)Selects elements within the set of elements defined by Bthat precede the n-th element (exclusive). Starts at 0. (‘div.someClass’) selects all div elements witha class name of someClassExamplesnnnnnnnnn (‘li p’) selects all p elements that are direct childrenof li elements (‘div p’) selects all div elements that are precededby a p elementn (‘.someClass’) selects all elements with class namesomeClassn (‘#testButton’) selects the element with the id valueof testButtonn (‘img[alt]’) selects all img elements that possessan alt attributen (‘a[href .pdf]’) selects all a elements thatpossess an href attribute that ends in .pdfn (‘button[id* test]’) selects all buttons whose idattributes contain testnnHotTipYou can create the union of multiple disparateselectors by listing them, separated by commas,in a single call to (). For example, the followingmatches all div and p elements:nn (‘div,p’)While the following, matches all div elementswith a title attribute, and all img elementswith alt attributes:nn (‘div[title],img[alt]’)nPositional SelectorsThese selectors match based upon positional relationshipsbetween elements. These selectors can be appended to anybase selector (which we’ll denote by B) to filter the matchesbased upon position. If B is omitted, it is assumed to be *(the pool of all elements).SyntaxDescriptionB:firstSelects the first element on the page matching the baseselector B.B:lastSelects the last element on the page matching the baseselector B.B:first-childSelects all elements from B that are first children.B:last-childSelects all elements from B that are last children.B:only-childSelects all elements from B that are only children.B:nth-child(n)Selects all elements from B that are n-th ordinal children.Starts at 1.B:nth-child(odd even)Selects all elements from B that are even or odd ordinalchildren. The first child is considered odd (ordinal 1).B:nth-child(Xn Y)B:even (‘p:first’) selects the first p element on the page (‘img[src .png]:first’) selects the first img element on the page that has a src attribute ending in .png (‘button.small:last’) selects the last button element on the page that has a class name of small (‘li:first-child’) selects all li elements that arefirst children within their lists (‘a:only-child’) selects all a elements that are theonly element within their parent (‘li:nth-child(2)’) selects all li elements thatare the second item within their lists (‘tr:nth-child(odd)’) selects all odd tr elementswithin a table (‘div:nth-child(5n)’) selects every 5th div element (‘div:nth-child(5n 1)’) selects the element afterevery 5th div element (‘.someClass:eq(1)’) selects the second elementwith a class name of someClass (‘.someClass:gt(1)’) selects all but the first twoelements with a class name of someClass (‘.someClass:lt(4)’) selects the first four elementswith a class name of someClassHotTipNote that the :nth-child selectors begincounting at 1, while the :eq , :gt and :ltselectors begin with 0.jQuery Custom SelectorsThese selectors are provided by jQuery to allow for commonlyused, or just plain handy, selections that were not anticipatedby the CSS Specification. Like the Positional Selectors, theseselectors filter a base matching set (which we denote with B).Omitting B is interpreted as the set of all elements. Theseselectors may be combined; see the examples for somepowerful selector combinations.Selects all elements from B that match the formula. X denotesan ordinal multiplier, while Y denotes an offset. Y may beomitted if 0. See the following examples.Selects the even elements within the set of elementsdefined by B.DZone, Inc. SyntaxDescriptionB:animatedSelects elements from the base set B that are currently underanimated control via one of the jQuery animation methods.B:buttonSelects elements of B that are of any button type; that is:button, input[type submit], input[type reset] orinput[type button].B:checkboxSelects elements of B that are of type input[type checkbox].www.dzone.com

3jQuery Selectorstech facts at your fingertipsjQuery Custom Selectors, continuedMATCHED SET METHODSSyntaxDescriptionB:enabledSelects form elements from B that are in enabled state.B:fileSelects elements of B that are of type input[type file].B:headerSelects elements from B that are of the header types:that is h1 through h6 .B:hiddenSelects elements of B that are hidden.B:imageSelects elements of B that are of type input[type image].B:inputSelects form input elements from B; that is, input , select , textarea and button elements.B:not(f)Selects elements of B that do not match the filter selector specifiedby f. A filter selector is any selector beginning with : (colon), A baseset B cannot be specified as part of f.B:parentSelects elements of B that are parents of non-empty elementchildren.B:passwordSelects elements of B that are of type input[type password].B:radioSelects elements of B that are of type input[type radio].add(expression)B:resetSelects elements of B that are of type input[type reset] orbutton[type reset].expressionB:selectedSelects elements of B that are in selected state. Only option elements posses this state.to create and add to the set.B:submitSelects elements of B that are of type input[type submit] orbutton[type submit].(Array) Array of references to elements to add.B:textSelects elements of B that are of type input[type text].B:visibleSelects form elements from B that are not hidden.While the jQuery selectors give us great flexibility in identifying which DOM elements are to be added to a matched set,sometimes there are match criteria that cannot be expressedby selectors alone. Also, given the power of jQuery methodchaining, we may wish to adjust the contents of the matchedset between method invocations.For these situations, jQuery provides methods that operatenot upon the elements within the matched set, but on thematched set itself. This section will summarize those methods.Adding New ElementsFor adding new elements to a matched set, the add() methodis provided:be added to the matched set, or an HTML string of new elements(Element) A reference to an existing element to add.The add() method returns a new matched set that is theunion of elements in the original wrapped set and any elementseither passed directly as the expression argument, ormatched by the selector of the expression argument.Examplesnnnnnnnnn(String) A selector expression that specifies the DOM elements to (‘img:animated’) selects all img elements that areundergoing animationConsider: (‘:button:hidden’) selects all button type elementsthat are hidden (‘input[name myRadioGroup]:radio:checked’)selects all radio elements with the name attribute value ofmyRadioGroup that are checkedThis statement creates a matched set of all div elements,then creates a new matched set of the already matched div elements and all p elements. The second matched set’s elements (all div and all p elements) are then given the CSScolor property of “red”. (‘:text:disabled’) selects all text fields that aredisabledYou may think this is not all that useful because the same couldhave been achieved with: ); (‘div,p’).css(‘color’,’red’); (‘#xyz p :header’) selects all header type elementswithin p elements that are within an element with an idvalue of xyz. Note the space before :header that preventsit from binding directly to the p.But now consider: ‘p’).css(‘color’,’red’); (‘option:not(:selected)’) selects all unselected option elementsHere the first created matched set of div elements is assigned a bold rendition, and then the second matched set,with p elements added, is colored red. (‘#myForm button:not(.someClass)’) selects allbuttons from the form with the id of myForm that do notpossess the class name someClass.jQuery chaining (in which the css() method returns thematched set) allows us to create efficient statements such asthis one that can accomplish a great deal with little in the wayof script. (‘select[name choices] :selected’) selects theselected option elements within the select elementnamed choices.More Examples (‘p:contains(coffee)’) selects all p elements thatcontain the text coffee px solidpink’);Used either separately, or in combination, the jQuery selectorsgive you a great deal of power to easily create a set of elementsthat you wish to operate upon with the jQuery methods.DZone, Inc. ’,’3px solid pink’); www.dzone.com

4jQuery Selectorstech facts at your fingertipsRemoving Matched Elementsfilter(expression)What if we want to remove elements from the matched set?That’s the job of the not() method:expression(String) A selector expression that specifies which elementsare to be retained.(Function) A function used to determine if an element shouldbe included in the new set or not. This function is passed thezero-based ordinal of the element within the original set, andthe function context (this) is set to the current element.Returning false as the function result causes the element tonot be included in the new set.not(expression)expression(String) A selector expression that specifies the DOM elementsto be removed from the matched set.(Element) A reference to an existing element to remove.(Array) Array of references to elements to remove.The filter() method can be passed either a selector expression(comma-separated if more than one is desired) or a function.When passed a selector, it acts like the inverse of not(),retaining elements that match the selector (as opposed toexcluding them). When passed a function, the function is invoked for each element and decisions that cannot be expressedby selectors can be made regarding the exclusion or inclusionof each element.Like add(), this method creates and returns a new matchedset, except with the elements specified by the expressionargument removed. The argument can be a jQuery selector, orreferences to elements to remove.Examples (‘body �).css(‘color’,’red’);Makes all body elements bold, then makes all but p elements red.Examples (‘body ent).css(‘color’,’red’); (‘.bashful’).show().filter(‘img[src .gif]’).attr(‘title’,’Hi there!’);Similar to the previous except the element referenced byvariable anElement is not included in the second set (andtherefore not colored red).HotTipSelects all elements with class name bashful, makes surethat they are visible, filters the set down to just GIF images,and assigns a title attribute to them. (‘img[src images/]’).filter(function(){Avoid a typical beginner’s mistake and neverconfuse the not() method, which will removeelements from the matched set, with theremove() method, which will remove theelements in the matched set from the HTML DOM!return (this).attr(‘title’).match(/. @. \.com/)! null;}).hide();Selects images from a specific folder, filters them to onlythose whose title attribute matches a rudimentary .comemail address, and hides those elements.Finding DescendantsSlicing and Dicing Matched SetsSometimes it’s useful to limit the search for elements todescendants of already identified elements. The find()method does just that:find(expression)Rather than matching elements by selector, we may sometimeswish to slice up a matched set based upon the position of theelements within the set. This section introduces two methodsthat do that for us.expressionBoth of these methods assume zero-based indexing.(String) A selector expression that specifies which descendantelements are to be matched.slice(being,end)Unlike the previously examined methods, find() only acceptsa selector expression as its argument. The elements within theexisting matched set will be searched for descendants thatmatch the expression. Any elements in the original matchedset that match the selector are not included in the new set.Examplebegin(Number) The beginning position of the first element tobe included in the new set.end(Number) The end position of the first element to not beincluded in the new set. If omitted, all elements from begin tothe end of the set are included.Examples .find(‘img’).css(‘border’,’1px solid aqua’);; (‘body *’).slice(2).hide();Selects all div elements, makes their background blue,selects all img elements that are descendants of those div elements (but not img elements that are notdescendants) and gives them an aqua border.Selects all body elements, then creates a new set containingall but the first two elements, and hides them. (‘body *’).slice(2,3).hide();Selects all body elements, then creates a new set containingthe third element in the set and hides it. Note that the newset contains just one element: that at position 2. The elementat position 3 is not included.Filtering Matched SetsWhen really fine-grained control is required for filtering the elements of a matched set, the filter() method comes in handy:DZone, Inc. www.dzone.com

5jQuery Selectorstech facts at your fingertipsSlicing and Dicing Matched Sets, continuedFor example, let’s say that you wanted to collect the values ofall form elements within a form named myForm:eq(position)positionvar values (‘#myForm :input’).map(function(){return (this).val();});(Number) The position of a single element to be included in thenew set.The eq(n) method can be considered shorthand forslice(n,n 1).Matching by RelationshipHotTipFrequently we may want to create new matched sets basedupon relationships between elements. These methods aresimilar enough that we’ll present them en masse in thefollowing table:MethodDescriptionchildren(expression)Creates a new matched set containing all uniquechildren of the elements in the original matched setthat match the optional expression.next(expression)Creates a new matched set containing uniquefollowing (next) siblings of the elements in theoriginal matched set that match the optionalexpression. Only immediately following siblingsare returned.nextAll(expression)var values (‘#myForm :input’).map(function(){return (this).val();}).get();In this case, values references a JavaScript array rather thana jQuery wrapped object.Controlling ChainingAll of the methods examined create new matched sets whosecontents are determined in the manner explained for eachmethod. But what happens to the original? Is it dismissed?Creates a new matched set containing uniquefollowing (next) siblings of the elements in theoriginal matched set that match the optionalexpression. All following siblings are returned.parent(expression)Creates a new matched set containing uniqueimmediate parents of the elements in the originalmatched set that match the optional expression.parents(expression)Creates a new matched set containing allancestors of the elements in the original matchedset that match the optional expression.prev(expression)Creates a new matched set containing uniquepreceding siblings of the elements in the originalmatched set that match the optional expression.Only immediately preceding siblings are returned.prevAll(expression)Creates a new matched set containing uniquepreceding siblings of the elements in the originalmatched set that match the optional expression. Allpreceding siblings are returned.siblings(expression)Creates a new matched set containing uniquesiblings of the elements in the original matched setthat match the optional expression.contents()Creates a new matched set containing all uniquechildren of the elements in the original matched setincluding text nodes. When used on an iframe ,matches the content document.The map() function returns a jQuery objectinstance. To convert this to a normal JavaScriptarray, you can use the get() method withoutparameters:It is not. When a new wrapped set is created it is placed on thetop of a stack of sets, with the top-most set being the oneto which any methods will be applied (as we have seen in theexamples). But jQuery allows you to “pop” the top-most setoff that stack so that you can apply methods to the originalset. It does this with the end() method:end()(no arguments)Consider a previous example: );As we recall, this creates a matched set of div elements,then creates a new set that also contains the p elements.Since this latter set is at the top of the stack when the css()method is called, it is the second set that is affected. Nowconsider: ).end().hide();After the css() method is called, the end() method popsthe second set off the stack “exposing” the original set of just div elements, which are then hidden.For all methods that accept a filtering expression, the expressionmay be omitted in which case no filtering occurs.Translating ElementsAnother useful method to affect how chaining the sets operatesis the andSelf() method:There may be times that you want to translate the elementswithin a matched set to other values. jQuery provides themap() method for this purpose.andSelf()(no arguments)map(callback)callbackCalling andSelf() creates yet another new matched set thatis the union of the top two matched sets on the stack. This canbe useful for performing an action on a set, creating a new(Function) A callback function called for each element in thematched set. The return values of the invocations are collectedinto an array that is returned as the result of the map() method.The current element is set as the function context (this) foreach invocation.DZone, Inc. www.dzone.com

6jQuery Selectorstech facts at your fingertipsmerged, and a wide margin is applied to all div elementsand their img children.Controlling Chaining, continueddistinct set, and then applying a method (or methods) to themall. Consider:Between jQuery selectors and the jQuery methods that allowus to manipulate the matched sets, we can see that jQuerygives us some powerful tools to select the DOM elementsthat we can then operate upon with the many jQuery methods(as well as the dozens and dozens of jQuery plugins) that areavailable to us. �).children(‘img’).css(‘border’,’4px ridge ll div elements are selected and their background set toyellow. Then, the img children of those div elements areselected and have a border applied. Finally, the two sets areABOUT THE AUTHORSRECOMMENDED BOOKBear BibeaultjQuery in Action is aBear Bibeault has been writing software for over three decades, starting with aTic-Tac-Toe program written on a Control Data Cyber supercomputer via a 100-baudteletype. He is a Software Architect and Technical Manager for a company that buildsand maintains a large financial web application used by the accountants that many ofthe Fortune 500 companies keep in their dungeons. He also serves as a “sheriff” atthe popular JavaRanch.com.fast-paced introductionand guide to thejQuery library. It showsyou how to traverseHTML documents,handle events, performPublications: jQuery in Action, Ajax in Practice, Prototype and Scriptaculous in Action (Manning)Notable Projects: “Sheriff” at JavaRanch.com, FrontMan Web Application Controlleranimations, and addAjax to your web pages using jQuery. YouYehuda KatzYehuda Katz has been involved in a number of open-source projects over the pastseveral years. In addition to being a core team member of the jQuery project, he isalso a core member of Merb, an alternative to Ruby on Rails (also written in Ruby).He speaks about jQuery and Ruby at a number of regional conferences, and is theJavaScript expert on the Merb team. He recently joined EngineYard working onthe Merb project full-time.Publication: jQuery in Action (Manning)Notable Projects: Visual jQuery.com, jQuery Plugin Coordinator, Merb, DataMapper ORMWeb site: www.yehudakatz.comlearn how jQuery interacts with other toolsand how to build jQuery plugins.BUY NOWbooks.dzone.com/books/jquery-in-actionGet More FREE Refcardz. Visit refcardz.com now!Upcoming Refcardz:Available:Core SeamEssential RubyEssential MySQLCore CSS: Part IJUnit and EasyMockCore .NETGetting Started with MyEclipseVery First Steps in FlexEquinoxSpring AnnotationsC#EMFCore JavaGroovyCore CSS: Part IINetBeans IDE 6.1 Java EditorPHPRSS and AtomJSP Expression LanguageGetting Started with JPAGlassFish Application ServerALM Best PracticesJavaServer FacesSilverlight 2Hibernate SearchXMLHTML and XHTMLStruts2FREEDesign PatternsPublished June 2008Visit refcardz.com for a complete listing of available Refcardz.DZone, Inc.1251 NW MaynardCary, NC 27513DZone communities deliver over 4 million pages each month tomore than 1.7 million software developers, architects and decisionmakers. DZone offers something for everyone, including news,tutorials, cheatsheets, blogs, feature articles, source code and more.“DZone is a developer’s dream,” says PC Magazine.ISBN-13: 978-1-934238-06-6ISBN-10: 1-934238-06-650795888.678.0399919.678.0300Refcardz Feedback Welcomerefcardz@dzone.comSponsorship Opportunitiessales@dzone.com 7.95Core CSS: Part III9 781934 238066Copyright 2008 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical,photocopying, or otherwise, without prior written permission of the publisher. Reference: jQuery in Action, Erich Gamma, Bear Bibeault and Yehuda Katz. Manning Publications, February 2008.Version 1.0

jQuery library. These selectors use familiar CSS syntax to allow page authors to quickly and easily identify any set of page elements to operate upon with the jQuery library methods. Understanding jQuery selectors is the key to using the jQuery library most effectively. This reference card pu

Related Documents:

elements to operate upon with the jQuery library methods. Understanding jQuery selectors is the key to using the jQuery library most effectively. This reference card puts the power of jQuery selectors at your very fingertips. A jQuery statement typically follows the syntax pattern: by any sibling of tag name E. (selector).methodName();

Chapter 1: Getting started with jQuery 2 Remarks 2 Versions 2 Examples 3 jQuery Namespace ("jQuery" and " ") 3 Getting Started 3 Explanation of code 4 Include script tag in head of HTML page 5 Avoiding namespace collisions 6 Loading jQuery via console on a page that does not have it. 8 The jQuery Object 8 Loading namespaced jQuery plugins 8 .

jQuery is the starting point for writing any jQuery code. It can be used as a function jQuery(.) or a variable jQuery.foo. is an alias for jQuery and the two can usually be interchanged for each other (except where jQuery.noConflict(); has been used - see Avoiding namespace collisions). Assuming we have this snippet of HTML -

jQuery is the starting point for writing any jQuery code. It can be used as a function jQuery(.) or a variable jQuery.foo. is an alias for jQuery and the two can usually be interchanged for each other (except where jQuery.noConflict(); has been used - see Avoiding namespace collisions). Assuming we have this snippet of HTML -

Cissp cheat sheet all domains. Cissp cheat sheet 2022 pdf. Cissp cheat sheet 2022. Cissp cheat sheet domain 4. Cissp cheat sheet pdf. Cissp cheat sheet 2021. Cissp cheat sheet domain 1. Cissp cheat sheet reddit. We use cookies to offer you a better browsing experience, analyze site traffic, personalize content, and serve targeted advertisements.

To get started with the jQuery UI library, you'll need to add the jQuery script, the jQuery UI script, and the jQuery UI stylesheet to your HTML. First, download jQuery UI; choose the features you need on the download page.

browsers. However, the jQuery team has taken care of this for us, so that we can write AJAX functionality with only one single line of code jQuery - AJAX load() Method jQuery load() Method The jQuery load() method is a simple, but powerful AJAX method. The load() method loads data from a server and puts the returned data into the selected element.

Andreas Wimmer, Indra de Soysa, Christian Wagner Number 61 Political Science Tools for Assessing Feasibility and Sustainability of Reforms ZEF – Discussion Papers on Development Policy Bonn, February 2003. The CENTER FORDEVELOPMENT RESEARCH (ZEF) was established in 1997 as an international, interdisciplinary research institute at the University of Bonn. Research and teaching at ZEF aims to .