jQuery

Articles
Deffered
Event
Custom Event
Cookie
Utility methods and objects
Plugins
Plugin Development
Scrolling and Animation
Performance
Custom Queue
AJAX
Forms
Validation
jQuery UI
Miscellaneous
Moving away from jQuery

http://www.w3schools.com/jquery/jquery_ref_selectors.asp - done reading
https://api.jquery.com/category/selectors/
http://codylindley.com/jqueryselectors/ - done reading
https://dzone.com/refcardz/jquery-selectors
https://api.jqueryui.com/data-selector/
http://learn.jquery.com/

<script type="text/javascript" charset="utf8" src="/srm/js/jquery-1.10.2.min.js"></script>

// JQuery:

// Form submission via AJAX:
var myForm =  $('#my-form');
jQuery.post('submit.php', myForm.serialize(), function(){
    alert('Data has been sent!');
});

// Making a regular AJAX call:
jQuery.ajax({
    url: '...?ServName=ManageUserSettings&sCheck=N&mode=GET_USER_SETTINGS',
    data: {},
    type: 'POST',
    success: function(data, textStatus, jqXHR ) {
        jQuery('#msgUpdate').html('User reset successfully!');
        setTimeout(function(){closeResetUnblockWindow();}, 800);
    }
});

// Check a check box:
jQuery('input.apInput[value=' + value + ']').prop('checked',true);

// Retrieve a list of check boxes that are checked
jQuery('#nearmissVersusActualCon input[type=checkbox]:checked');

// Select a particular option from a select box
$('.selDiv option:eq(1)').prop('selected', true);

// Event delegation:
jQuery("body").on( "click", '.apInputQuickSelect', function(){});

// Check version:
$().jquery;
jQuery.fn.jquery;

// DOM Ready:
$(document).ready(function() { ... });
$(function(){ ... });

// IIFE:
(function($){})(jQuery);

$('img[alt], img[title]') // combine multiple selectors into one
$('img[alt]').add('img[title]') // add additional elements to the wrapped set
$('img[title]:not([title*=puppy])')
$('img[title]').not('[title*=puppy]');
$('p:even')
$('tr:nth-child(1)')
$('body div')
$('body > div')
$('a[href$=pdf]') // select all anchor tags that are PDFs
$('body > div:has(a)')  // select DIVs containing links
$.trim(someString)
$('table tr:nth-child(even)').addClass("even")
$(document).ready(function(){});
$(function(){});
jQuery.noConflict();
$('htmlTagName')
$('#specialID')
$('.cssClassName')
$('htmlTagName#specialID.className')
$('p a.className')  // matches anchor tag with className and is inside a <p> element
$('a[href^=http://])
$('form[method]')  // select an element with a particular attribute regardless of the value of the attribute
input[type=text]
div[title^=my]
a[href$=.pdf]
a[href*=jquery.com]
li:has(a)  // select li elements that contains an anchor tag, only a single level of nesting is supported
foo:not(bar:has(baz))
foo:not(bar:has(baz:eq(2))) // this is not supported

* // matches any element
E // matches all elements with tag name E
E F // matches all elements with tag name F that are descendant of E
E > F // matches all elements with tag name F that are direct descendant of E
E + F // matches all elements with tag name F that are immediately preceded by sibling E
E - F // matches all elements with tag name F preceded by sibling E
E:has(F) // matches all elements with tag name E that have at least one descendant with tag name F
E.C // matches all elements with tag name E with class name C
.C // matches all elements with class name C
E#I // matches an element with tag name E that has the ID of I.
#I // matches an element that has the ID of I
E[A] // matches all elements with tag name E that has attribute A of any value
E[A=V] // matches all elements with tag name E that has attribute A whose value is exactly V
E[A^=V] // matches all elements with tag name E that has attribute A whose value starts with V
E[A$=V] // matches all elements with tag name E that has attribute A whose value ends with V
E[A*=V] // matches all elements with tag name E that has attribute A whose value contains V
a:first // matches the first <a> on the page
p:odd // matches odd paragraph elements
p:even // matches even paragraph elements
li:last-child // matches the last <li> child of each <ul> element
:first // The first match of the page
li a:first // match the first link under a list item
:last // The last child of the page.
li a:last // match the last link under a list item
:first-child // The first child element
li:first-child // match the first <li> of each list
:last-child // The last child element
li:last-child // matches the last <li> of each list
:only-child // matches all elements that have no siblings
:nth-child(n) // The nth child element
li:nth-child(2) // matches the second list item of each list
:nth-child(even|odd) // match even or odd children
li:nth-child(even) // matches the even children of each list
:nth-child(Xn+Y) // The nth child element by the supplied formula.  If Y is 0, it may be omitted.
li:nth-child(3n) // matches every 3rd item
li:nth-child(5n+1) // matches the item after every 5 element
:even // matches even element page-wide
:odd // matches odd element page-wide
li:even // matches every even list item.
li:odd // matches every odd list item
:eq(n) // matches nth element
:gt(n) // matches elements after and excluding the nth matching element
:lt(n) // matches elements before and excluding the nth matching element

:checkbox:checked
:radio:checked

:animated // elements that are currently under animated control
:button // matches any button (input[type=submit], input[type=reset], input[type=button], or button)
:contains(foo) // matches only elements containing the text foo.
:disabled // match form elements that are disabled
:enabled // match only form elements that are enabled
:file // matches all file element (input[type=file])
:header // select all header elements (h1, h2, ...)
:hidden // select only elements that are hidden
:image // selects form images (input[type=image])
:input // select only form elements (input, select, textarea, button)
:not(filter) // Negate the specified filter
input:not(:checkbox) // select all input elements that are not check boxes
div p:not(:hidden)
:parent // selects only elements that have children (including text), but not empty element.
:password // select only password elements (input[type=password])
:checkbox
:radio
:reset // selects reset buttons (input[type=reset] or button[type=reset])
:selected // selects option elements that are selected
:submit // select the submit buttons (input[type=submit] or button[type=submit])
:text // select only text elements (input[type=text])
:visible // selects only elements that are visible
:checkbox:checked:enabled // matches check boxes that are checked and are enabled.

/html//form/fieldset  // selects all fieldset elements that are directly under a form element on a page
/html//form/*/input // selects all <input> elements directly under exactly one element that is under a <form> element
//div/.. // selects all elements that are directly parent to a <div> element
//div[@foo=bar]  // selects all <div> elements with attribute foo=bar
//div[@p]  // selects <div> elements containing at eleast one <p> element
position()=0  // select the first element, similar to :first
position()>n // select elements with position greater than n, similar to :gt(n)

What are available methods?

.slice(begin, end)
.slice(2, 3)
.slice(4) 
.children(expression) // returns a wrapped set consisting of all unique children of the wrapped elements
.content() // returns a wrapped set of the contents of the elements, which may include text nodes
               // in the wrapped set.  Frequently used to obtain the contents of <iframe> element
.next(expression) // returns a wrapped set consisting of all unique next siblings of the wrapped elements
.nextAll(expression) // returns a wrapped set containing all of the following sibling of the wrapped elements
.parent(expression) // returns a wrapped set consisting of the unique direct parents of all wrapped elements
.parents(expression) // returns a wrapped set consisting of unique ancestors of all wrapped elements.
.prev(expression) // returns a wrapped set consisting of all unique previous siblings of the wrapped elements
.prevAll(expression) // returns a wrapped set containing all the previous siblings of the wrapped elements
.siblings(expression) // returns a wrapped set consisting of all unique siblings of the wrapped elements
.contains(text) // select elements that contains the specified text.
var hasImage = $('*').is('img') // returns true if the wrapped set contains an image
.andSelf() // merge the two previous wrapped sets in a command chain.

$('img').each(function(n) {
  this.alt = 'This is image[' + n + '] with an id of ' + this.id;
});
// Inside the iterator function, the this context is the DOM element

var attributeName = .attr('attributeName')
.attr('attributeName', 'attributeValue')
.attr({ ... })
$('input').attr({ value: '', title: 'Please enter a value' })
// The .attr also take a iterator function.  See the documentation for detail.
.removeAttr('attributeName')

$('form').submit(function(){
  $(':submit', this).attr('disabled','disabled');
});

.addClass('className')
.addClass(classNames)
.removeClass('className')
.removeClass(classNames)
.toggleClass
.hasClass
.html
.text
.append
$('p').append('<b>some text</b>');
$('p.appendToMe').append($('a.appendMe'));
prepend
prependTo
before
insertBefore
after
insertAfter
wrap
wrapAll
remove
empty
clone
val
end

How can we check a checkbox?

jQuery('input.apInput[value=' + value + ']').prop('checked',true);

How can we select all the check boxes that are checked?

jQuery('#nearmissVersusActualCon input[type=checkbox]:checked')

How can we select a particular option from a select box?

$('.selDiv option:eq(1)').prop('selected', true);

How can we use the .map method to map over a jQuery collection?

When we use the map function, we pass it an array and a callback (transform) function. The map function iterate over the elements of the array / collection, and for each element of the array, the map function invoke the transform function, passing it the particular element, the transform function can do whatever it wants with the element.

_.map([1, 2, 3], function(num){ return num * 3; });

The above code use the .map method from the Underscore library, and it returns:

[3, 6, 9]

The transform function can have advanced if/else logic. For each element, it can return the result of a simple calculation, or it can return an array (in which case the result array will have more elements than the original array), or it does not return any value (in which case, the result array will have less elements than the original array). I ACTUALLY NEED TO VERIFY THIS AT LEAST WITH THE Underscore LIBRARY.

Use the .map method to map over a jQuery collection. If we want to map over an array, use the jQuery.map method. To map over a jQuery collection:

var tagIDs = $('input.tags[type=checkbox]:checked').map(function(i,dom){
  return dom.value;
}).get();

The above code query the DOM for all check boxes that are checked. We then use the .map method to iterate over this jQuery collection, and returns an array of values. By default, the .map function returns a jQuery collection. We have to use the .get() method at the end because we want tagIDs to be a regular JavaScript array.

How can we do event delegation?

jQuery("body").on( "click", '.apInputQuickSelect', function(){});

How can we select elements that does not have any child nodes?

$(":not(:has(*))")

The :has() selector "selects elements which contain at least one element that matches the specified selector." The wildcard * means all elements.

How can we select all rows except the first row?

$(":not(:first)")
$(":not(:eq(0))")
$("*").not(":eq(0)")
$(":gt(0)")
$("*").gt(0)

What are various ways to select elements?

$("*")
$("#id")
$('.className')
$('tagName')
$('tagName.className');
$('selector1, selector2, selector3, ...');
$(this); // Takes a DOM element and turn it into a wrapped set
$("div > p"); // selects all <p> elements that are a direct child of a <div> element
$("div p"); // selects all <p> elements that are descendants of a <div> element
$("div + p"); // selects all <p> element that are next (sibling) to each <div> elements in the forward (next) order
$("div ~ p"); // selects all <p> elements that are siblings of a <div> element in any order

$(":contains('Hello')"); // selects elements which contains the text "Hello"
$("p:contains(coffee)") selects all <p> elements that contain the text coffee

$("input:not(:empty)"); // selects all input elements that are not empty
$(":focus"); // selects the element that currently has focus
$(":input"); // selects all input elements
$(":text"); // selects all input elements with type="text"
$(":password"); // selects all input elements with type="password"
$(":radio"); // selects all input elements with type="radio"
$(":checkbox"); // selects all input elements with type="checkbox"
$(":submit"); // selects all input elements with type="submit"
$(":reset"); // selects all input elements with type="reset"
$(":button"); // selects all input elements with type="button"
$(":image"); // selects all input elements with type="image"
$(":file"); // selects all input elements with type="file"
$(":enabled"); // selects all enabled input elements
$(":disabled"); // selects all disabled input elements
$(":selected"); // selects all selected input elements
$(":checked"); // selects all checked input elements
$("option:not(:selected)") selects all unselected <option> elements
$("#myForm button:not(.someClass)") selects all buttons from the <form> with the id of myForm that do not possess the class name someClass.
$("select[name=choices] :selected") selects the selected <option> elements within the <select> element named choices.

$("[href]"); // selects all elements that have the href attribute
$("[href='default.htm']"); // selects all elements with a href attribute value equal to "default.htm"
$("[href!='default.htm']"); // selects all elements with a href attribute value not equal to "default.htm"
$("[href$='.jpg']"); // selects all elements with a href attribute value ending with ".jpg"
$("[title|='Tomorrow']"); // selects all elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
$("[title^='Tom']"); // selects all elements with a title attribute value starting with "Tom"
$("[title~='hello']"); // selects all elements with a title attribute value containing the specific word "hello"
$("[title*='hello']"); // All elements with a title attribute value containing the word "hello"

$("div:has(p)"); // selects all <div> elements that have a <p> element
$(":empty"); // selects all elements that are empty
$(":parent"); // selects all elements that are a parent of another element
$("p:hidden"); // selects all hidden <p> elements
$("table:visible"); // selects all visible tables
$(":root"); // selects the document's root element
$("p:lang(de)"); // selects all <p> elements with a lang attribute value starting with "de"

$("p:first"); // Select the first p
$("p:last"); // Select the last p
$("tr:even"); // selects all even tr elements
$("tr:odd"); // selects all odd tr elements
$("a:only-child") selects all <a> elements that are the only element within their parent
$("p:only-child"); // selects all p elements that are the only child of their parent

$("p:first-child"); // selects all p elements that are the first child of their parent
$("li:first-child") selects all <li> elements that are first children within their lists

$("p:first-of-type"); // selects all p elements that are the first <p> element of their parent (may not be the first child)
$("p:last-child"); // selects all p elements that are the last child of their parent
$("p:last-of-type"); // select all p elements that are the last <p> element of their parent

$("p:nth-child(2)"); // selects all p elements that are the 2nd child of their parent
$("p:nth-child(odd|even)"); // selects all p elements that are odd / even child of their parents
$("p:nth-child(Xn+Y)"); // selects all p elements that are
$("li:nth-child(2)") selects all <li> elements that are the second item within their lists
$("tr:nth-child(odd)") selects all odd <tr> elements within a table
$("div:nth-child(5n)") selects every 5th <div> element
$("div:nth-child(5n+1)") selects the element after every 5th <div> element

$("p:nth-last-child(2)"); // selects all p elements that are the 2nd child of their parent, counting from the last child
$("p:nth-of-type(2)"); // selects all p elements that are the 2nd <p> element of their parent
$("p:nth-last-of-type(2)"); // selects all p elements that are the 2nd <p> element of their parent, counting from the last child

$(".someClass:eq(1)") selects the second element with a class name of someClass
$("ul li:eq(3)"); // selects all fourth element in a list (index starts at 0)

$(".someClass:gt(1)") selects all but the first two elements with a class name of someClass
$("ul li:gt(3)"); // selects all li elements with an index greater than 3

$(".someClass:lt(4)") selects the first four elements with a class name of someClass
$("ul li:lt(3)"); // selects all li elements with an index less than 3

$("p:only-of-type"); //selects all p elements that are the only child, of its type, of their parent

$(":header"); // selects all header elements <h1>, <h2> ...

$(":animated"); // selects all animated elements

Note that the :nth-child selectors begin counting at 1, while the :eq, :gt and :lt selectors begin with 0.

A filter selector is any selector beginning with colon (:)

How can we check the version of jQuery?

$().jquery;
jQuery.fn.jquery;

How can we run a function when the DOM is ready?

$(document).ready(function() { ... });

jQuery(function(){ ... });
$(function($){ ... });  // Not much different from the above, but inside the ready handler, $ is the jQuery object.

How can we map $ to jQuery?

(function($){})(jQuery);

This is if you have some other library loaded and you want to use $ as jQuery in the body of your function. The first part, '(function($){})' defines an anonymous function, and enclose it in the parentheses to make an expression out of it, resulting in a reference to the anonymous function being returned as the value of the expression. The function expects a single parameter, which is named '$'. Whatever is passed to this function can be referenced by the $ identifier within the body of this function. And because parameter declarations have precedence over any similarly named identifiers in the global scope, any value defined for $ outside the function is supereded within the function by the passed argument.

The second part, '(jQuery)' execute the function passing the jQuery object as the argument.

How can we obtain the raw DOM element?

jQuery('#id').get(0)

How can we append raw HTML to an existing element?

jQuery(html).appendTo(existingElementSelector);

How can we create a jQuery collection from a string?

jQuery can create a collection from a string. You can do anything with this collection just as you would do with any jQuery collection before inserting into the DOM.

Central to jQuery's DOM capabilities, is its element creation syntax. jQuery 1.4 brought with it an entirely new way to create your elements quickly and succinctly:

var myDiv = jQuery('<div/>', {
    id: 'my-new-element',
    class: 'foo',
    css: {
        color: 'red',
        backgrondColor: '#FFF',
        border: '1px solid #CCC'
    },
    click: function() {
        alert('Clicked!');
    },
    html: jQuery('<a/>', {
        href: '#',
        click: function() {
            // do something
            return false;
        }
    })
});

As of 1.4 you can pass a second argument to the jQuery function when you're creating an element — the object you pass will, for the most part, act as if you were passing it to '.attr(…)'. However, jQuery will map some of the properties to its own methods, for example, the 'click' property maps to jQuery's 'click' method (which binds an event handler for the 'click' event) and 'css' maps to jQuery's 'css' method etc.

All methods that appear to mutate the collection in some way return a brand new jQuery object — you can still access the old object though, via '.end()', or more verbosely, via '.prevObject'.

How can we obtain the selector that was used to query the DOM?

var jq = jQuery('...');
var selector = jq.selector;

var jqObject = jQuery('a');
jqObject.selector; // => "a"

How can we use event delegation?

function doSomething(ev) {
    ...
    ev.preventDefault();
    console.log( $( this ).text() );
}
jQuery("body").on( "click", "#addNewUserCancel", doSomething);

How can we write a custom utility function?

Utility functions are defined as properties of jQuery (and therefore $). These functions are not intended to operate on DOM elements. That is the job of methods defined to operate on a wrapped set. Utility functions are to either operate on a non-element JavaScript object or perform some other nonobject-specific operation. Examples: $.each(), and $.noConflict().

Adding a utility function to jQuery is as easy as declaring the function and assigning it to the object's property. So creating a custom utility function should be as easy as:

(function($){
    $.say = function(what) {
        alert('I say ' + what);
    }
})(jQuery);

jQuery methods:

.height(). Get or set the current computed height for the first element in the set of matched elements or set the height of every matched element.

.innerHeight(). Get the current computed inner height (including padding but not border) for the first element in the set of matched elements or set the inner height of every matched element.

.innerWidth(). Get the current computed inner width (including padding but not border) for the first element in the set of matched elements or set the inner width of every matched element.

.outerHeight(). Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns a number (without “px”) representation of the value or null if called on an empty set of elements.

.outerWidth(). Get the current computed width for the first element in the set of matched elements, including padding and border.

.width(). Get the current computed width for the first element in the set of matched elements or set the width of every matched element.

jQuery.contains( container, contained ): Check to see if a DOM element is a descendant of another DOM element. The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

$.contains( document.documentElement, document.body ); // true
$.contains( document.body, document.documentElement ); // false

Why does the nth-child selectors start with 1 instead of 0?

It just does. The nth-child selector starts counting from 1, whereas other selectors start counting from 0. For CSS compatibility, nth-child starts with 1, but the jQuery custom selectors follow the more common programming convention of starting at 0.

Why should we not select all checked check boxes using the attribute selector?

We might want to select all check boxes that have been checked by the user. Because trying to match by attribute will only check the initial state of the control as specified in the HTML markup. jQuery offers a custom selector, ':checked', that filters the set of matched elements to those that are in checked state.

input:checked

The above code selects all input elements that are checked.

How can we select all radio boxes that are checked?

:radio:checked

How can we select all check boxes that are checked?

:checkbox:checked

What is the purpose of the .end() method?

Terminate the effect of the .filter and returns the original wrapped set.

Is there any difference between .length and .size()?

They are are the same, except that .length an attribute and .size() is a method.

$('a').length
$('a').size()

What is the purpose of the .get() method?

We can use the .get() method to obtain a DOM element within a wrapped set at the given index, or to obtain a list of DOM elements within the wrapped set when we do not specify an index:

$('a').get(0)
$('a').get()

What is the purpose of the .index() method?

Find the passed element in the wrapped set and returns its ordinal index within the set. If the element isn't in the set, the value -1 is returned.

var n = $('img').index($('img#findMe')[0]);

Notice that the parameter to the .index() method must be a DOM element.

What is the purpose of the .not() method?

not(expression)

Remove elements from the matched set according to the value of the expression parameter.

What is the purpose of the .filter() method?

When passed a function, the filter() method invokes that function for each wrapped element and removes any element whose function invocation return false. Each invocation has access to the current wrapped element via the function context (this).

The filter() method can also be used with a passed selector expression that conforms to the same constraints for the .not() method. When used in this manner, it operates in the inverse manner than the corresponding not() method, removing any elements that do not match the passed selector.

$('img').addClass('seeThrough').filter('[title*=dog]').addClass('thickBorder')
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License