jQuery Notes for Professionals (GoalKicker.com Stack Overflow Documentation) (Z-Library)

Author: GoalKicker.com, Stack Overflow Documentation

非小说

The jQuery® Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA. See credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified Book created for educational purposes and is not affiliated with jQuery® group(s), company(s) nor Stack Overflow. All trademarks belong to their respective company owners.

📄 File Format: PDF
💾 File Size: 966.0 KB
46
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
jQuery Notes for ProfessionalsjQuery® Notes for Professionals GoalKicker.com Free Programming Books Disclaimer This is an unocial free book created for educational purposes and is not aliated with ocial jQuery® group(s) or company(s). All trademarks and registered trademarks are the property of their respective owners 50+ pages of professional hints and tricks
📄 Page 2
Contents About 1 ................................................................................................................................................................................... Chapter 1: Getting started with jQuery 2 ............................................................................................................. Section 1.1: Getting Started 2 ........................................................................................................................................... Section 1.2: Avoiding namespace collisions 3 ................................................................................................................ Section 1.3: jQuery Namespace ("jQuery" and "$") 4 ................................................................................................... Section 1.4: Loading jQuery via console on a page that does not have it 5 .............................................................. Section 1.5: Include script tag in head of HTML page 5 ................................................................................................ Section 1.6: The jQuery Object 7 ..................................................................................................................................... Chapter 2: Ajax 8 ............................................................................................................................................................... Section 2.1: Handling HTTP Response Codes with $.ajax() 8 ....................................................................................... Section 2.2: Using Ajax to Submit a Form 9 ................................................................................................................... Section 2.3: All in one examples 9 ................................................................................................................................... Section 2.4: Ajax File Uploads 11 .................................................................................................................................... Chapter 3: Selectors 14 .................................................................................................................................................. Section 3.1: Overview 14 ................................................................................................................................................... Section 3.2: Types of Selectors 14 .................................................................................................................................. Section 3.3: Caching Selectors 16 ................................................................................................................................... Section 3.4: Combining selectors 17 ............................................................................................................................... Section 3.5: DOM Elements as selectors 19 ................................................................................................................... Section 3.6: HTML strings as selectors 19 ...................................................................................................................... Chapter 4: document-ready event 21 ................................................................................................................... Section 4.1: What is document-ready and how should I use it? 21 ............................................................................. Section 4.2: jQuery 2.2.3 and earlier 21 .......................................................................................................................... Section 4.3: jQuery 3.0 22 ................................................................................................................................................ Section 4.4: Attaching events and manipulating the DOM inside ready() 22 ............................................................ Section 4.5: Dierence between $(document).ready() and $(window).load() 23 ..................................................... Section 4.6: Dierence between jQuery(fn) and executing your code before </body> 24 ..................................... Chapter 5: DOM Manipulation 25 .............................................................................................................................. Section 5.1: Creating DOM elements 25 ......................................................................................................................... Section 5.2: Manipulating element classes 25 ............................................................................................................... Section 5.3: Other API Methods 27 .................................................................................................................................. Chapter 6: DOM Traversing 29 ................................................................................................................................... Section 6.1: Select children of element 29 ...................................................................................................................... Section 6.2: Get next element 29 ..................................................................................................................................... Section 6.3: Get previous element 29 ............................................................................................................................. Section 6.4: Filter a selection 30 ...................................................................................................................................... Section 6.5: find() method 31 .......................................................................................................................................... Section 6.6: Iterating over list of jQuery elements 32 ................................................................................................... Section 6.7: Selecting siblings 32 ..................................................................................................................................... Section 6.8: closest() method 32 ..................................................................................................................................... Chapter 7: Element Visibility 34 ................................................................................................................................. Section 7.1: Overview 34 ................................................................................................................................................... Section 7.2: Toggle possibilities 34 ................................................................................................................................. Chapter 8: Events 36 ....................................................................................................................................................... Section 8.1: Delegated Events 36 .................................................................................................................................... Section 8.2: Attach and Detach Event Handlers 37 ......................................................................................................
📄 Page 3
Section 8.3: Switching specific events on and o via jQuery. (Named Listeners) 38 ................................................ Section 8.4: originalEvent 39 ........................................................................................................................................... Section 8.5: Events for repeating elements without using ID's 39 ............................................................................... Section 8.6: Document Loading Event .load() 40 .......................................................................................................... Chapter 9: Plugins 41 ....................................................................................................................................................... Section 9.1: Plugins - Getting Started 41 ......................................................................................................................... Chapter 10: Prepend 43 .................................................................................................................................................. Section 10.1: Prepending an element to a container 43 ................................................................................................ Section 10.2: Prepend method 43 ................................................................................................................................... Chapter 11: Append 45 .................................................................................................................................................... Section 11.1: Ecient consecutive .append() usage 45 .................................................................................................. Section 11.2: jQuery append 48 ....................................................................................................................................... Section 11.3: Appending an element to a container 48 ................................................................................................. Chapter 12: Getting and setting width and height of an element 50 ..................................................... Section 12.1: Getting and setting width and height (ignoring border) 50 .................................................................... Section 12.2: Getting and setting innerWidth and innerHeight (ignoring padding and border) 50 ......................... Section 12.3: Getting and setting outerWidth and outerHeight (including padding and border) 50 ....................... Chapter 13: CSS Manipulation 51 ............................................................................................................................... Section 13.1: CSS – Getters and Setters 51 ...................................................................................................................... Section 13.2: Increment/Decrement Numeric Properties 51 ........................................................................................ Section 13.3: Set CSS property 52 .................................................................................................................................... Section 13.4: Get CSS property 52 ................................................................................................................................... Chapter 14: Attributes 53 .............................................................................................................................................. Section 14.1: Dierece between attr() and prop() 53 .................................................................................................... Section 14.2: Get the attribute value of a HTML element 53 ........................................................................................ Section 14.3: Setting value of HTML attribute 54 ........................................................................................................... Section 14.4: Removing attribute 54 ............................................................................................................................... Chapter 15: jQuery .animate() Method 55 ............................................................................................................ Section 15.1: Animation with callback 55 ........................................................................................................................ Chapter 16: jQuery Deferred objects and Promises 57 ................................................................................. Section 16.1: jQuery ajax() success, error VS .done(), .fail() 57 ..................................................................................... Section 16.2: Basic promise creation 57 ......................................................................................................................... Chapter 17: Checkbox Select all with automatic check/uncheck on other checkbox change 59 .............................................................................................................................................................................. Section 17.1: 2 select all checkboxes with corresponding group checkboxes 59 ....................................................... Chapter 18: Each function 60 ....................................................................................................................................... Section 18.1: jQuery each function 60 ............................................................................................................................. Credits 61 .............................................................................................................................................................................. You may also like 64 ........................................................................................................................................................
📄 Page 4
GoalKicker.com – jQuery® Notes for Professionals 1 About Please feel free to share this PDF with anyone for free, latest version of this book can be downloaded from: https://goalkicker.com/jQueryBook This jQuery® Notes for Professionals book is compiled from Stack Overflow Documentation, the content is written by the beautiful people at Stack Overflow. Text content is released under Creative Commons BY-SA, see credits at the end of this book whom contributed to the various chapters. Images may be copyright of their respective owners unless otherwise specified This is an unofficial free book created for educational purposes and is not affiliated with official jQuery® group(s) or company(s) nor Stack Overflow. All trademarks and registered trademarks are the property of their respective company owners The information presented in this book is not guaranteed to be correct nor accurate, use at your own risk Please send feedback and corrections to web@petercv.com
📄 Page 5
GoalKicker.com – jQuery® Notes for Professionals 2 Chapter 1: Getting started with jQuery Version Notes Release Date 1.0 First stable release 2006-08-26 1.1 2007-01-14 1.2 2007-09-10 1.3 Sizzle introduced into core 2009-01-14 1.4 2010-01-14 1.5 Deferred callback management, ajax module rewrite 2011-01-31 1.6 Significant performance gains in the attr() and val() methods 2011-05-03 1.7 New Event APIs: on() and off(). 2011-11-03 1.8 Sizzle rewritten, improved animations and $(html, props) flexibility. 2012-08-09 1.9 Removal of deprecated interfaces and code cleanup 2013-01-15 1.10 Incorporated bug fixes and differences reported from both the 1.9 and 2.0 beta cycles 2013-05-24 1.11 2014-01-24 1.12 2016-01-08 2.0 Dropped IE 6–8 support for performance improvements and reduction in size 2013-04-18 2.1 2014-01-24 2.2 2016-01-08 3.0 Massive speedups for some jQuery custom selectors 2016-06-09 3.1 No More Silent Errors 2016-07-07 3.2 No More Silent Errors 2017-03-16 3.3 No More Silent Errors 2018-01-19 Section 1.1: Getting Started Create a file hello.html with the following content: <!DOCTYPE html> <html> <head> <title>Hello, World!</title> </head> <body> <div> <p id="hello">Some random text</p> </div> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> <script> $(document).ready(function() { $('#hello').text('Hello, World!'); }); </script> </body> </html> Live Demo on JSBin Open this file in a web browser. As a result you will see a page with the text: Hello, World! Explanation of code
📄 Page 6
GoalKicker.com – jQuery® Notes for Professionals 3 Loads the jQuery library from the jQuery CDN:1. <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> This introduces the $ global variable, an alias for the jQuery function and namespace. Be aware that one of the most common mistakes made when including jQuery is failing to load the library BEFORE any other scripts or libraries that may depend on or make use of it. Defers a function to be executed when the DOM (Document Object Model) is detected to be "ready" by2. jQuery: // When the `document` is `ready`, execute this function `...` $(document).ready(function() { ... }); // A commonly used shorthand version (behaves the same as the above) $(function() { ... }); Once the DOM is ready, jQuery executes the callback function shown above. Inside of our function, there is3. only one call which does 2 main things: Gets the element with the id attribute equal to hello (our selector #hello). Using a selector as the1. passed argument is the core of jQuery's functionality and naming; the entire library essentially evolved from extending document.querySelectorAllMDN. Set the text() inside the selected element to Hello, World!.2. # ↓ - Pass a `selector` to `$` jQuery, returns our element $('#hello').text('Hello, World!'); # ↑ - Set the Text on the element For more refer to the jQuery - Documentation page. Section 1.2: Avoiding namespace collisions Libraries other than jQuery may also use $ as an alias. This can cause interference between those libraries and jQuery. To release $ for use with other libraries: jQuery.noConflict(); After calling this function, $ is no longer an alias for jQuery. However, you can still use the variable jQuery itself to access jQuery functions: jQuery('#hello').text('Hello, World!'); Optionally, you can assign a different variable as an alias for jQuery: var jqy = jQuery.noConflict();
📄 Page 7
GoalKicker.com – jQuery® Notes for Professionals 4 jqy('#hello').text('Hello, World!'); Conversely, to prevent other libraries from interfering with jQuery, you can wrap your jQuery code in an immediately invoked function expression (IIFE) and pass in jQuery as the argument: (function($) { $(document).ready(function() { $('#hello').text('Hello, World!'); }); })(jQuery); Inside this IIFE, $ is an alias for jQuery only. Another simple way to secure jQuery's $ alias and make sure DOM is ready: jQuery(function( $ ) { // DOM is ready // You're now free to use $ alias $('#hello').text('Hello, World!'); }); To summarize, jQuery.noConflict() : $ no longer refers to jQuery, while the variable jQuery does. var jQuery2 = jQuery.noConflict() - $ no longer refers to jQuery, while the variable jQuery does and so does the variable jQuery2. Now, there exists a third scenario - What if we want jQuery to be available only in jQuery2? Use, var jQuery2 = jQuery.noConflict(true) This results in neither $ nor jQuery referring to jQuery. This is useful when multiple versions of jQuery are to be loaded onto the same page. <script src='https://code.jquery.com/jquery-1.12.4.min.js'></script> <script> var jQuery1 = jQuery.noConflict(true); </script> <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script> <script> // Here, jQuery1 refers to jQuery 1.12.4 while, $ and jQuery refers to jQuery 3.1.0. </script> https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/ Section 1.3: jQuery Namespace ("jQuery" and "$") 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 - <div id="demo_div" class="demo"></div>
📄 Page 8
GoalKicker.com – jQuery® Notes for Professionals 5 We might want to use jQuery to add some text content to this div. To do this we could use the jQuery text() function. This could be written using either jQuery or $. i.e. - jQuery("#demo_div").text("Demo Text!"); Or - $("#demo_div").text("Demo Text!"); Both will result in the same final HTML - <div id="demo_div" class="demo">Demo Text!</div> As $ is more concise than jQuery it is the generally the preferred method of writing jQuery code. jQuery uses CSS selectors and in the example above an ID selector was used. For more information on selectors in jQuery see types of selectors. Section 1.4: Loading jQuery via console on a page that does not have it Sometimes one has to work with pages that are not using jQuery while most developers are used to have jQuery handy. In such situations one can use Chrome Developer Tools console ( F12 ) to manually add jQuery on a loaded page by running following: var j = document.createElement('script'); j.onload = function(){ jQuery.noConflict(); }; j.src = "https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"; document.getElementsByTagName('head')[0].appendChild(j); Version you want might differ from above(1.12.4) you can get the link for one you need here. Section 1.5: Include script tag in head of HTML page To load jQuery from the official CDN, go to the jQuery website. You'll see a list of different versions and formats available.
📄 Page 9
GoalKicker.com – jQuery® Notes for Professionals 6 Now, copy the source of the version of jQuery, you want to load. Suppose, you want to load jQuery 2.X, click uncompressed or minified tag which will show you something like this: Copy the full code (or click on the copy icon) and paste it in the <head> or <body> of your html. The best practice is to load any external JavaScript libraries at the head tag with the async attribute. Here is a demonstration: <!DOCTYPE html> <html> <head> <title>Loading jquery-2.2.4</title> <script src="https://code.jquery.com/jquery-2.2.4.min.js" async></script> </head> <body> <p>This page is loaded with jquery.</p> </body> </html>
📄 Page 10
GoalKicker.com – jQuery® Notes for Professionals 7 When using async attribute be conscious as the javascript libraries are then asynchronously loaded and executed as soon as available. If two libraries are included where second library is dependent on the first library is this case if second library is loaded and executed before first library then it may throw an error and application may break. Section 1.6: The jQuery Object Every time jQuery is called, by using $() or jQuery(), internally it is creating a new instance of jQuery. This is the source code which shows the new instance: // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); } Internally jQuery refers to its prototype as .fn, and the style used here of internally instantiating a jQuery object allows for that prototype to be exposed without the explicit use of new by the caller. In addition to setting up an instance (which is how the jQuery API, such as .each, children,filter, etc. is exposed), internally jQuery will also create an array-like structure to match the result of the selector (provided that something other than nothing, undefined, null, or similar was passed as the argument). In the case of a single item, this array- like structure will hold only that item. A simple demonstration would be to find an element with an id, and then access the jQuery object to return the underlying DOM element (this will also work when multiple elements are matched or present). var $div = $("#myDiv");//populate the jQuery object with the result of the id selector var div = $div[0];//access array-like structure of jQuery object to get the DOM Element
📄 Page 11
GoalKicker.com – jQuery® Notes for Professionals 8 Chapter 2: Ajax Parameter Details url Specifies the URL to which the request will be sent settings an object containing numerous values that affect the behavior of the request type The HTTP method to be used for the request data Data to be sent by the request success A callback function to be called if the request succeeds error A callback to handle error statusCode An object of numeric HTTP codes and functions to be called when the response has the corresponding code dataType The type of data that you're expecting back from the server contentType Content type of the data to sent to the server. Default is "application/x-www-form-urlencoded; charset=UTF-8" context Specifies the context to be used inside callbacks, usually this which refers to the current target. Section 2.1: Handling HTTP Response Codes with $.ajax() In addition to .done, .fail and .always promise callbacks, which are triggered based on whether the request was successful or not, there is the option to trigger a function when a specific HTTP Status Code is returned from the server. This can be done using the statusCode parameter. $.ajax({ type: {POST or GET or PUT etc.}, url: {server.url}, data: {someData: true}, statusCode: { 404: function(responseObject, textStatus, jqXHR) { // No content found (404) // This code will be executed if the server returns a 404 response }, 503: function(responseObject, textStatus, errorThrown) { // Service Unavailable (503) // This code will be executed if the server returns a 503 response } } }) .done(function(data){ alert(data); }) .fail(function(jqXHR, textStatus){ alert('Something went wrong: ' + textStatus); }) .always(function(jqXHR, textStatus) { alert('Ajax request was finished') }); As official jQuery documentation states: If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.
📄 Page 12
GoalKicker.com – jQuery® Notes for Professionals 9 Section 2.2: Using Ajax to Submit a Form Sometimes you may have a form and want to submit it using ajax. Suppose you have this simple form - <form id="ajax_form" action="form_action.php"> <label for="name">Name :</label> <input name="name" id="name" type="text" /> <label for="name">Email :</label> <input name="email" id="email" type="text" /> <input type="submit" value="Submit" /> </form> The following jQuery code can be used (within a $(document).ready call) - $('#ajax_form').submit(function(event){ event.preventDefault(); var $form = $(this); $.ajax({ type: 'POST', url: $form.attr('action'), data: $form.serialize(), success: function(data) { // Do something with the response }, error: function(error) { // Do something with the error } }); }); Explanation var $form = $(this) - the form, cached for reuse $('#ajax_form').submit(function(event){ - When the form with ID "ajax_form" is submitted run this function and pass the event as a parameter. event.preventDefault(); - Prevent the form from submitting normally (Alternatively we can use return false after the ajax({}); statement, which will have the same effect) url: $form.attr('action'), - Get the value of the form's "action" attribute and use it for the "url" property. data: $form.serialize(), - Converts the inputs within the form into a string suitable for sending to the server. In this case it will return something like "name=Bob&email=bob@bobsemailaddress.com" Section 2.3: All in one examples Ajax Get: Solution 1: $.get('url.html', function(data){ $('#update-box').html(data); }); Solution 2:
📄 Page 13
GoalKicker.com – jQuery® Notes for Professionals 10 $.ajax({ type: 'GET', url: 'url.php', }).done(function(data){ $('#update-box').html(data); }).fail(function(jqXHR, textStatus){ alert('Error occurred: ' + textStatus); }); Ajax Load: Another ajax get method created for simplcity $('#update-box').load('url.html'); .load can also be called with additional data. The data part can be provided as string or object. $('#update-box').load('url.php', {data: "something"}); $('#update-box').load('url.php', "data=something"); If .load is called with a callback method, the request to the server will be a post $('#update-box').load('url.php', {data: "something"}, function(resolve){ //do something }); Ajax Post: Solution 1: $.post('url.php', {date1Name: data1Value, date2Name: data2Value}, //data to be posted function(data){ $('#update-box').html(data); } ); Solution 2: $.ajax({ type: 'Post', url: 'url.php', data: {date1Name: data1Value, date2Name: data2Value} //data to be posted }).done(function(data){ $('#update-box').html(data); }).fail(function(jqXHR, textStatus){ alert('Error occurred: ' + textStatus); }); Ajax Post JSON: var postData = { Name: name, Address: address, Phone: phone }; $.ajax({ type: "POST", url: "url.php",
📄 Page 14
GoalKicker.com – jQuery® Notes for Professionals 11 dataType: "json", data: JSON.stringfy(postData), success: function (data) { //here variable data is in JSON format } }); Ajax Get JSON: Solution 1: $.getJSON('url.php', function(data){ //here variable data is in JSON format }); Solution 2: $.ajax({ type: "Get", url: "url.php", dataType: "json", data: JSON.stringfy(postData), success: function (data) { //here variable data is in JSON format }, error: function(jqXHR, textStatus){ alert('Error occurred: ' + textStatus); } }); Section 2.4: Ajax File Uploads 1. A Simple Complete Example We could use this sample code to upload the files selected by the user every time a new file selection is made. <input type="file" id="file-input" multiple> var files; var fdata = new FormData(); $("#file-input").on("change", function (e) { files = this.files; $.each(files, function (i, file) { fdata.append("file" + i, file); }); fdata.append("FullName", "John Doe"); fdata.append("Gender", "Male"); fdata.append("Age", "24"); $.ajax({ url: "/Test/Url", type: "post", data: fdata, //add the FormData object to the data parameter processData: false, //tell jquery not to process data
📄 Page 15
GoalKicker.com – jQuery® Notes for Professionals 12 contentType: false, //tell jquery not to set content-type success: function (response, status, jqxhr) { //handle success }, error: function (jqxhr, status, errorMessage) { //handle error } }); }); Now let's break this down and inspect it part by part. 2. Working With File Inputs This MDN Document ( Using files from web applications ) is a good read about various methods on how to handle file inputs. Some of these methods will also be used in this example. Before we get to uploading files, we first need to give the user a way to select the files they want to upload. For this purpose we will use a file input. The multiple property allows for selecting more than one files, you can remove it if you want the user to select one file at a time. <input type="file" id="file-input" multiple> We will be using input's change event to capture the files. var files; $("#file-input").on("change", function(e){ files = this.files; }); Inside the handler function, we access the files through the files property of our input. This gives us a FileList, which is an array like object. 3. Creating and Filling the FormData In order to upload files with Ajax we are going to use FormData. var fdata = new FormData(); FileList we have obtained in the previous step is an array like object and can be iterated using various methods including for loop, for...of loop and jQuery.each. We will be sticking with the jQuery in this example. $.each(files, function(i, file) { //... }); We will be using the append method of FormData to add the files into our formdata object. $.each(files, function(i, file) { fdata.append("file" + i, file); }); We can also add other data we want to send the same way. Let's say we want to send some personal information we have received from the user along with the files. We could add this this information into our formdata object. fdata.append("FullName", "John Doe");
📄 Page 16
GoalKicker.com – jQuery® Notes for Professionals 13 fdata.append("Gender", "Male"); fdata.append("Age", "24"); //... 4. Sending the Files With Ajax $.ajax({ url: "/Test/Url", type: "post", data: fdata, //add the FormData object to the data parameter processData: false, //tell jquery not to process data contentType: false, //tell jquery not to set content-type success: function (response, status, jqxhr) { //handle success }, error: function (jqxhr, status, errorMessage) { //handle error } }); We set processData and contentType properties to false. This is done so that the files can be send to the server and be processed by the server correctly.
📄 Page 17
GoalKicker.com – jQuery® Notes for Professionals 14 Chapter 3: Selectors A jQuery selectors selects or finds a DOM (document object model) element in an HTML document. It is used to select HTML elements based on id, name, types, attributes, class and etc. It is based on existing CSS selectors. Section 3.1: Overview Elements can be selected by jQuery using jQuery Selectors. The function returns either an element or a list of elements. Basic selectors $("*") // All elements $("div") // All <div> elements $(".blue") // All elements with class=blue $(".blue.red") // All elements with class=blue AND class=red $(".blue,.red") // All elements with class=blue OR class=red $("#headline") // The (first) element with id=headline $("[href]") // All elements with an href attribute $("[href='example.com']") // All elements with href=example.com Relational operators $("div span") // All <span>s that are descendants of a <div> $("div > span") // All <span>s that are a direct child of a <div> $("a ~ span") // All <span>s that are siblings following an <a> $("a + span") // All <span>s that are immediately after an <a> Section 3.2: Types of Selectors In jQuery you can select elements in a page using many various properties of the element, including: Type Class ID Possession of Attribute Attribute Value Indexed Selector Pseudo-state If you know CSS selectors you will notice selectors in jQuery are the same (with minor exceptions). Take the following HTML for example: <a href="index.html"></a> <!-- 1 --> <a id="second-link"></a> <!-- 2 --> <a class="example"></a> <!-- 3 --> <a class="example" href="about.html"></a> <!-- 4 --> <span class="example"></span> <!-- 5 --> Selecting by Type: The following jQuery selector will select all <a> elements, including 1, 2, 3 and 4. $("a")
📄 Page 18
GoalKicker.com – jQuery® Notes for Professionals 15 Selecting by Class The following jQuery selector will select all elements of class example (including non-a elements), which are 3, 4 and 5. $(".example") Selecting by ID The following jQuery selector will select the element with the given ID, which is 2. $("#second-link") Selecting by Possession of Attribute The following jQuery selector will select all elements with a defined href attribute, including 1 and 4. $("[href]") Selecting by Attribute Value The following jQuery selector will select all elements where the href attribute exists with a value of index.html, which is just 1. $("[href='index.html']") Selecting by Indexed Position (Indexed Selector) The following jQuery selector will select only 1, the second <a> ie. the second-link because index supplied is 1 like eq(1) (Note that the index starts at 0 hence the second got selected here!). $("a:eq(1)") Selecting with Indexed Exclusion To exclude an element by using its index :not(:eq()) The following selects <a> elements, except that with the class example, which is 1 $("a").not(":eq(0)") Selecting with Exclusion To exclude an element from a selection, use :not() The following selects <a> elements, except those with the class example, which are 1 and 2. $("a:not(.example)") Selecting by Pseudo-state You can also select in jQuery using pseudo-states, including :first-child, :last-child, :first-of-type, :last- of-type, etc. The following jQuery selector will only select the first <a> element: number 1.
📄 Page 19
GoalKicker.com – jQuery® Notes for Professionals 16 $("a:first-of-type") Combining jQuery selectors You can also increase your specificity by combining multiple jQuery selectors; you can combine any number of them or combine all of them. You can also select multiple classes, attributes and states at the same time. $("a.class1.class2.class3#someID[attr1][attr2='something'][attr3='something']:first-of-type:first- child") This would select an <a> element that: Has the following classes: class1, class2, and class3 Has the following ID: someID Has the following Attribute: attr1 Has the following Attributes and values: attr2 with value something, attr3 with value something Has the following states: first-child and first-of-type You can also separate different selectors with a comma: $("a, .class1, #someID") This would select: All <a> elements All elements that have the class class1 An element with the id #someID Child and Sibling selection jQuery selectors generally conform to the same conventions as CSS, which allows you to select children and siblings in the same way. To select a non-direct child, use a space To select a direct child, use a > To select an adjacent sibling following the first, use a + To select a non-adjacent sibling following the first, use a ~ Wildcard selection There might be cases when we want to select all elements but there is not a common property to select upon (class, attribute etc). In that case we can use the * selector that simply selects all the elements: $('#wrapper *') // Select all elements inside #wrapper element Section 3.3: Caching Selectors Each time you use a selector in jQuery the DOM is searched for elements that match your query. Doing this too often or repeatedly will decrease performance. If you refer to a specific selector more than once you should add it to the cache by assigning it to a variable: var nav = $('#navigation'); nav.show();
📄 Page 20
GoalKicker.com – jQuery® Notes for Professionals 17 This would replace: $('#navigation').show(); Caching this selector could prove helpful if your website needs to show/hide this element often. If there are multiple elements with the same selector the variable will become an array of these elements: <div class="parent"> <div class="child">Child 1</div> <div class="child">Child 2</div> </div> <script> var children = $('.child'); var firstChildText = children[0].text(); console.log(firstChildText); // output: "Child 1" </script> NOTE: The element has to exist in the DOM at the time of its assignment to a variable. If there is no element in the DOM with a class called child you will be storing an empty array in that variable. <div class="parent"></div> <script> var parent = $('.parent'); var children = $('.child'); console.log(children); // output: [] parent.append('<div class="child">Child 1</div>'); children = $('.child'); console.log(children[0].text()); // output: "Child 1" </script> Remember to reassign the selector to the variable after adding/removing elements in the DOM with that selector. Note: When caching selectors, many developers will start the variable name with a $ to denote that the variable is a jQuery object like so: var $nav = $('#navigation'); $nav.show(); Section 3.4: Combining selectors Consider following DOM Structure <ul class="parentUl"> <li> Level 1 <ul class="childUl"> <li>Level 1-1 <span> Item - 1 </span></li> <li>Level 1-1 <span> Item - 2 </span></li> </ul> </li>
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List