jQuery: The Write Less, Do More JavaScript Library

API/1.1.2/Core

From jQuery JavaScript Library

(Redirected from Core)
Jump to: navigation, search

This section describes core functionality that comes with jQuery. The following subsections describe each of these absolutely essential functions, e.g. you will find documentation on how to...

$( html )

Create DOM elements on-the-fly from the provided String of raw HTML.

Return value: jQuery
Parameters:

  • html (String): A string of HTML to create on the fly.

Example:

Creates a div element (and all of its contents) dynamically, and appends it to the body element. Internally, an element is created and its innerHTML property set to the given markup. It is therefore both quite flexible and limited.

 $("<div><p>Hello</p></div>").appendTo("body")

$( elems )

Wrap jQuery functionality around a single or multiple DOM Element(s).

This function also accepts XML Documents and Window objects as valid arguments (even though they are not DOM Elements).

Return value: jQuery
Parameters:

  • elems (Element|Array<Element>): DOM element(s) to be encapsulated by a jQuery object.

Example:

Sets the background color of the page to black.

 $(document.body).css( "background", "black" );

Example:

Hides all the input elements within a form

 $( myForm.elements ).hide()

$( fn )

A shorthand for $(document).ready(), allowing you to bind a function to be executed when the DOM document has finished loading. This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready to be operated on. While this function is, technically, chainable - there really isn't much use for chaining against it.

You can have as many $(document).ready events on your page as you like.

See ready(Function) for details about the ready event.

Return value: jQuery
Parameters:

  • fn (Function): The function to execute when the DOM is ready.

Example:

Executes the function when the DOM is ready to be used.

 $(function(){
   // Document is ready
 });

Example:

Uses both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias.

 jQuery(function($) {
   // Your code using failsafe $ alias here...
 });

$( expr, context )

This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements.

The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS or XPath), which then finds all matching elements.

By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.

See DOM/Traversing/Selectors for the allowed CSS/XPath syntax for expressions.

Return value: jQuery
Parameters:

  • expr (String): An expression to search with
  • context (Element|jQuery): (optional) A DOM Element, Document or jQuery to use as context

Example:

Finds all p elements that are children of a div element.

 $("div > p")
Before:
 <p>one</p> <div><p>two</p></div> <p>three</p>
Result:
 [ <p>two</p> ]


Example:

Searches for all inputs of type radio within the first form in the document

 $("input:radio", document.forms[0])

Example:

This finds all div elements within the specified XML document.

 $("div", xml.responseXML)

$.fn.extend( prop )

Extends the jQuery object itself. Can be used to add functions into the jQuery namespace and to add plugin methods (plugins).

Return value: Object
Parameters:

  • prop (Object): The object that will be merged into the jQuery object

Example:

Adds two plugin methods.

 jQuery.fn.extend({
   check: function() {
     return this.each(function() { this.checked = true; });
   },
   uncheck: function() {
     return this.each(function() { this.checked = false; });
   }
 });
 $("input[@type=checkbox]").check();
 $("input[@type=radio]").uncheck();

Example:

Adds two functions into the jQuery namespace

 jQuery.extend({
   min: function(a, b) { return a < b ? a : b; },
   max: function(a, b) { return a > b ? a : b; }
 });

$.noConflict()

Run this function to give control of the $ variable back to whichever library first implemented it. This helps to make sure that jQuery doesn't conflict with the $ object of other libraries.

By using this function, you will only be able to access jQuery using the 'jQuery' variable. For example, where you used to do $("div p"), you now must do jQuery("div p").

Return value: undefined
Example:

Maps the original object that was referenced by $ back to $

 jQuery.noConflict();
 // Do something with jQuery
 jQuery("div p").hide();
 // Do something with another library's $()
 $("content").style.display = 'none';

Example:

Reverts the $ alias and then creates and executes a function to provide the $ as a jQuery alias inside the functions scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library.

 jQuery.noConflict();
 (function($) { 
   $(function() {
     // more code using $ as alias to jQuery
   });
 })(jQuery);
 // other code using $ as an alias to the other library


each( fn )

Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the 'this' keyword points to the specific DOM element.

Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).

Return value: jQuery
Parameters:

  • fn (Function): A function to execute

Example:

Iterates over two images and sets their src property

 $("img").each(function(i){
   this.src = "test" + i + ".jpg";
 });
Before:
 <img/><img/>
Result:
 <img src="test0.jpg"/><img src="test1.jpg"/>


Example:

If you want to have the jQuery object instead of the regular DOM element, use the $(this) function, for example:

$("img").each(function(){
  $(this).toggleClass("example");
});


Example:

You can use 'return' to break out of each() loops early.

$("img").each(function(){
  if ( $(this).is(":hidden") )
    return false;
});


eq( pos )

Reduce the set of matched elements to a single element. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Return value: jQuery
Parameters:

  • pos (Number): The index of the element that you wish to limit to.

Example:

 $("p").eq(1)
Before:
 <p>This is just a test.</p><p>So is this</p>
Result:
 [ <p>So is this</p> ]


get()

Access all matched DOM elements. This serves as a backwards-compatible way of accessing all matched elements (other than the jQuery object itself, which is, in fact, an array of elements).

It is useful if you need to operate on the DOM elements themselves instead of using built-in jQuery functions.

Return value: Array<Element>
Example:

Selects all images in the document and returns the DOM Elements as an Array

 $("img").get();
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 [ <img src="test1.jpg"/> <img src="test2.jpg"/> ]


The reverse function to obtain a jquery object from a dom element is

$(domElement)

get( num )

Access a single matched DOM element at a specified index in the matched set. This allows you to extract the actual DOM element and operate on it directly without necessarily using jQuery functionality on it.

Return value: Element
Parameters:

  • num (Number): Access the element in the Nth position.

Example:

Selects all images in the document and returns the first one

 $("img").get(0);
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 <img src="test1.jpg"/>


gt( pos )

Reduce the set of matched elements to all elements after a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Return value: jQuery
Parameters:

  • pos (Number): Reduce the set to all elements after this position.

Example:

 $("p").gt(0)
Before:
 <p>This is just a test.</p><p>So is this</p>
Result:
 [ <p>So is this</p> ]


index( subject )

Searches every matched element for the object and returns the index of the element, if found, starting with zero. Returns -1 if the object wasn't found.

Return value: Number
Parameters:

  • subject (Element): Object to search for

Example:

Returns the index for the element with ID foobar

 $("*").index( $('#foobar')[0] )
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>
Result:
 0


Example:

Returns the index for the element with ID foo within another element

 $("*").index( $('#foo')[0] )
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>
Result:
 2


Example:

Returns -1, as there is no element with ID bar

 $("*").index( $('#bar')[0] )
Before:
 <div id="foobar"><b></b><span id="foo"></span></div>
Result:
 -1



length

The number of elements currently matched. The size function will return the same value.

Return value: Number
Example:

 $("img").length;
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 2


lt( pos )

Reduce the set of matched elements to all elements before a given position. The position of the element in the set of matched elements starts at 0 and goes to length - 1.

Return value: jQuery
Parameters:

  • pos (Number): Reduce the set to all elements below this position.

Example:

 $("p").lt(1)
Before:
 <p>This is just a test.</p><p>So is this</p>
Result:
 [ <p>This is just a test.</p> ]



size()

Get the number of elements currently matched. This returns the same number as the 'length' property of the jQuery object.

Return value: Number
Example:

 $("img").size();
Before:
 <img src="test1.jpg"/> <img src="test2.jpg"/>
Result:
 2