jQuery API

jQuery()

Contents:

jQuery( selector, [ context ] ) Returns: jQuery

Description: Accepts a string containing a CSS selector which is then used to match a set of elements.

  • version added: 1.0jQuery( selector, [ context ] )

    selectorA string containing a selector expression

    contextA DOM Element, Document, or jQuery to use as context

  • version added: 1.0jQuery( element )

    elementA DOM element to wrap in a jQuery object.

  • version added: 1.0jQuery( elementArray )

    elementArrayAn array containing a set of DOM elements to wrap in a jQuery object.

  • version added: 1.0jQuery( jQuery object )

    jQuery objectAn existing jQuery object to clone.

  • version added: 1.4jQuery()

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements:

$('div.foo');

Selector Context

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, if within a callback function we wish to do a search for an element, we can restrict that search:

$('div.foo').click(function() {
  $('span', this).addClass('bar');
});

Since we've restricted the span selector to the context of this, only spans within the clicked element will get the additional class.

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

Using DOM elements

The second and third formulations of this function allow us to create a jQuery object using a DOM element or elements that we have already found in some other way. A common use of this facility is to call jQuery methods on an element that has been passed to a callback function through the keyword this:

$('div.foo').click(function() {
  $(this).slideUp();
});

This example causes elements to be hidden with a sliding animation when clicked. Because the handler receives the clicked item in the this keyword as a bare DOM element, the element must be wrapped in a jQuery object before we can call jQuery methods on it.

When XML data is returned from an Ajax call, we can use the $() function to wrap it in a jQuery object that we can easily work with. Once this is done, we can retrieve individual elements of the XML structure using .find() and other DOM traversal methods.

Cloning jQuery Objects

When a jQuery object is passed as a parameter to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

Returning an Empty Set

As of jQuery 1.4, calling the jQuery() method with no arguments returns an empty jQuery set. In previous versions of jQuery, this would return a set containing the document node.

Examples:

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

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>one</p> <div><p>two</p></div> <p>three</p>
<script>$("div > p").css("border", "1px solid gray");</script>

</body>
</html>

Demo:

Result:

[ <p>two</p> ] 

Example: Finds all inputs of type radio within the first form in the document.

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

Example: Finds all div elements within an XML document from an Ajax response.

$("div", xml.responseXML);

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()

jQuery( html, [ ownerDocument ] ) Returns: jQuery

Description: Creates DOM elements on the fly from the provided string of raw HTML.

  • version added: 1.0jQuery( html, [ ownerDocument ] )

    htmlA string of HTML to create on the fly. Note that this parses HTML, not XML.

    ownerDocumentA document in which the new elements will be created

  • version added: 1.4jQuery( html, props )

    htmlA string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).

    propsAn map of attributes, events, and methods to call on the newly-created element.

Creating New Elements

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it has <tag ... > somewhere within the string). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML. Then a jQuery object is created and returned that refers to these elements. We can perform any of the usual jQuery methods on this object:

$('<p id="test">My <em>new</em> text</p>').appendTo('body');

When the HTML is more complex than a single tag without attributes, as it is in the above example, the actual creation of the elements is handled by the browser's innerHTML mechanism. Specifically, jQuery creates a new <div> element and sets the innerHTML property of the element to the HTML snippet that was passed in. When the parameter has a single tag, such as $('<img />') or $('<a></a>'), jQuery creates the element using the native JavaScript createElement() function.

To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:

$('<a href="http://jquery.com"></a>');

Alternatively, jQuery allows XML-like tag syntax (with or without a space before the slash):

$('<a/>');

Tags that cannot contain elements may be quick-closed or not:

$('<img />');
$('<input>');

As of jQuery 1.4, we can pass a map of properties to the second argument. This argument accepts a superset of properties that can be passed to the .attr() method. Furthermore, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset. Note that Internet Explorer will not allow you to create an input element and change its type; you must specify the type using '<input type="checkbox" />' for example.

Examples:

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")

Example: Create some DOM elements.

$("<div/>", {
  "class": "test",
  text: "Click me!",
  click: function(){
    $(this).toggleClass("test");
  }
}).appendTo("body");

$("<input>", {
  type: "text",
  val: "Test",
  focusin: function() {
    $(this).addClass("active");
  },
  focusout: function() {
    $(this).removeClass("active");
  }
}).appendTo("form");

jQuery( callback ) Returns: jQuery

Description: Binds a function to be executed when the DOM has finished loading.

  • version added: 1.0jQuery( callback )

    callbackThe function to execute when the DOM is ready.

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. While this function is, technically, chainable, there really isn't much use for chaining against it.

Examples:

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...
});

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for jQuery() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • Havvy
    "This argument accepts a superset of properties that can be passed to the .attr() method. Furthermore, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset."

    How does it know which is an attribute and which is an event type? Does it catch custom events?
  • Mathew
    a good cite fro reference
  • hello everyone i want to ask that is it necessary to create anonymous functions for event handlers such as focusin,focusout even if the event requires only one statement to be executed?
  • I'e searched high and low in the documentation and I can't seem to find out how to properly add the hover event (without any anonymous functions) upon element creation.

    This doesn't seem to work:
    $('<div>', {
    click: object.clickEvent,
    hover: (object.mouseOverEvent, object.mouseOutEvent)
    }).appendTo(containingDiv)

    But this does:
    $('<div>', {
    click: object.clickEvent,
    mouseenter: object.mouseOverEvent,
    mouseleave: object.mouseOutEvent
    }).appendTo(containingDiv)

    Any ideas?</div></div>
  • mouseleave: object.mouseOutEvent
  • Yeikos
    var content = '<script>var x = 1;';
    $(content).find('script')[0]; // >> undefined

    why?</script>
  • ...because .find() traverses "down."

    $(content)[0]; // >> <script>
  • Yeikos
    but i dont know where is script tag, i want use the selector for search in a string like in a DOM

    thanks for reply
  • It isn't in the DOM yet. You have just created a disconnected node. And it isn't a string at that point. I'm confused about why you would have a need to do this if you're creating a single script element. In any case, this is turning into a support request, so if you would be so kind as to seek help on the jQuery forum, I would greatly appreciate it.

    thanks
  • Kecs
    What if there s more than one $(function(){...}), because of several linked script?
  • The $ variable will belong to whichever script was linked to last, since later definitions override earlier ones. If jQuery is linked to last, you can call jQuery.noConflict() to revert $ to its second-to-last definition.
  • Ok, that example:

    jQuery('<div>',{
    class : 'myclass',
    css : {
    "position":"absolute",
    "left": "10px",
    "top" : "20px",
    "display" : "none",
    "z-index" : "90000"
    }
    }).appendTo("body");

    Not works in IE, that message is: Unexpected identifier, string or number :S
    </div>
  • Try putting the class part in quotes, like so: (class is a reserved word)

    jQuery('<div>',{
    "class" : 'myclass',
    "css" : {
    "position":"absolute",
    "left": "10px",
    "top" : "20px",
    "display" : "none",
    "z-index" : "90000"
    }
    }).appendTo("body");</div>
  • Rob
    It would be useful if the documentation would give more information on specifying an owner document when adding newly created HTML.
  • Caesura2
    Hi,

    In this example :

    $("<div>", {
    "class": "test",
    text: "Click me!",
    click: function(){
    $(this).toggleClass("test");
    }
    }).appendTo("body");

    Why are the props in braces (I assume that's the props list, as in the definition "jQuery( html, props )") ? And why is class in quotes and the other props not in quotes?

    And also why does the defintion say "jQuery ..." and the examples all begin with a dollar sign?

    Very confusing for a newbie who likes to learn by precise definitions of language syntax!</div>
  • The braces {} are a shorthand in Javascript to create an object, and are equivalent to the "new Object()" syntax.
    BTW, you can also create an array using square brackets [] in a similar way, being equivalent to the "new Array()" syntax.

    The dollar $ is an alias to the jQuery class, that may be used as a shorthand to save typing (and look cooler ;)), so $() and jQuery() are equivalent.

    As for "class" being in quotes (it also works without the quotes), I guess it's just to show that it's possible to do it that way, should you want to avoid conflict with a global variable or javascript keyword.

    EDIT: Oops, didn't see there were already many replies.. :)
  • Jesse Hemminger
    I think that the props parameter must be an object, that is why they are in braces. The braces make an object literal.

    I think class is quotes because class is probably a keyword (reserved word, javascript has lots of them that aren't even used). If class wasn't in quotes javascript would try to interpret it as a keyword and you would get an error. Because it is in quotes it is interpreted as a string and used as a property name.
  • Class must be in quotes cause it IS a reserved Keyword. But Firefox wont throw any error, only Webkit :/
  • bengarnett
    Most examples show $(function() { }) at the top of the script. Picked up a nice tip from Alex Sexton...a very nice variation of the normal usage:
    <script>
    // make an ajax request right away
    $.ajax({
    url: 'ajax.php',
    success: function(data) {
    $(document).ready(function(){ //<-- Hey Guys check this out!
    //do stuff
    });
    }
    });
    </script>

    Only the success function waits for the DOM ready. http://alexsexton.com/?p=22
  • bronson
    "jQuery examines the string to see if it looks like HTML"

    How? Must the HTML string begin with '<'?
Time to generate: 1.33776