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

    objectA plain object 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');

If no elements match the provided selector, the new jQuery object is "empty"; that is, it contains no elements and has .length property of 0.

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, to do a search within an event handler, the search can be restricted like so:

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

When the search for the span selector is restricted 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 create a jQuery object using one or more DOM elements that were already selected 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 passed to the $() function before applying jQuery methods to it.

XML data returned from an Ajax call can be passed to the $() function so individual elements of the XML structure can be retrieved using .find() and other DOM traversal methods.

$.post('url.xml', function(data) {
  var $child = $(data).find('child');
})

Cloning jQuery Objects

When a jQuery object is passed 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 (with a .length property of 0). In previous versions of jQuery, this would return a set containing the document node.

Working With Plain Objects

At present, the only operations supported on plain JavaScript objects wrapped in jQuery are: .data(),.prop(),.bind(), .unbind(), .trigger() and .triggerHandler(). The use of .data() (or any method requiring .data()) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).

// define a plain object
var foo = {foo:'bar', hello:'world'};

// wrap this with jQuery
var $foo = $(foo);

// test accessing property values
var test1 = $foo.prop('foo'); // bar

// test setting property values
$foo.prop('foo', 'foobar');
var test2 = $foo.prop('foo'); // foobar

// test using .data() as summarized above
$foo.data('keyName', 'someValue');
console.log($foo); // will now contain a jQuery{randomNumber} property

// test binding an event name and triggering
$foo.bind('eventName', function (){
        console.log('eventName was called');
});

$foo.trigger('eventName'); // logs 'eventName was called'

Should .trigger('eventName') be used, it will search for an 'eventName' property on the object and attempt to execute it after any attached jQuery handlers are executed. It does not check whether the property is a function or not. To avoid this behavior, .triggerHandler('eventName') should be used instead.

$foo.triggerHandler('eventName'); // also logs 'eventName was called'

Examples:

Example: Find all p elements that are children of a div element and apply a border to them.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.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:

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

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

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

$("div", xml.responseXML);

Example: Set the background color of the page to black.

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

Example: Hide 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. You can perform any of the usual jQuery methods on this object:

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

If 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. In most cases, 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.

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

Filtering isn't however just limited to these tags. For example, Internet Explorer prior to version 8 will also convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

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>');

When passing HTML to jQuery(), please also note that text nodes are not treated as DOM elements. With the exception of a few methods (such as .content()), they are generally otherwise ignored or removed. E.g:

var el = $('1<br/>2<br/>3'); // returns [<br>, "2", <br>] 
el  = $('1<br/>2<br/>3 >'); // returns [<br>, "2", <br>, "3 &gt;"]

This behaviour is expected.

As of jQuery 1.4, the second argument to jQuery() can accept a map consisting of a superset of the 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. The name "class" must be quoted in the map since it is a JavaScript reserved word, and "className" cannot be used since it is not the correct attribute name.

Note: Internet Explorer will not allow you to create an input or button element and change its type; you must specify the type using '<input type="checkbox" />' for example. A demonstration of this can be seen below:

Unsupported in IE:

$('<input />', {
    type: 'text',
    name: 'test'
}).appendTo("body");

Supported workaround:

$('<input type="text" />').attr({
    name: 'test'
}).appendTo("body");

Examples:

Example: Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup.

$("<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");

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: Execute the function when the DOM is ready to be used.

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

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

Support and Contributions

Need help with jQuery() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • bronson

    “jQuery examines the string to see if it looks like HTML”

    How? Must the HTML string begin with '<'?

    • http://www.learningjquery.com/ Karl Swedberg

      It doesn't need to begin with '<. jQuery uses a regular expression to inspect the string, and the part of it that tests for an HTML-string match is ^[^<]*(<[wW]+>)[^>]*$.

      In case you're not very familiar with regular expressions, it basically checks for something that looks like an HTML tag anywhere within the string.

  • MarcusT

    With regard to the use of jQuery(callback) for executing code when the document is ready, it has never been clear from the documentation whether you can do this any number of times (perhaps at different places in the HTML document) and be assured that each chunk of code will be called after each other, or whether each use of jQuery(callback) overwrites the previous call. While the answer can of course be found by simply testing, this shouldn't be necessary to be sure, and hence I'd like to see this made abundantly clear in the documentation with an explicit statement.

  • Anonymous

    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:

    // make an ajax request right away
    $.ajax({
    url: ‘ajax.php’,
    success: function(data) {
    $(document).ready(function(){ //<– Hey Guys check this out!
    //do stuff
    });
    }
    });

    Only the success function waits for the DOM ready. http://alexsexton.com/?p=22

  • Anonymous

    Hi,

    In this example :

    $(“”, {
    “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!

    • 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.

      • http://edgespan.de/ Alexander Trefz

        Class must be in quotes cause it IS a reserved Keyword. But Firefox wont throw any error, only Webkit :/

    • http://danielbrinca.com/ Daniel Brinca

      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.. :)

  • http://openid-provider.appspot.com/mrajcok Mark Rajcok

    At the beginning of the documentation, I think it would be very helpful (for those new to jQuery) to state that $() is an alias for jQuery().

    The wording in “Creating New Elements” seems to imply that tags that CAN contain elements should be XML-like and contain the trailing slash. If this is true, the last example in that section should be updated to include the slash:
    $(“<div/>”, { <<—- note “/” added
    “class”: “test”,

    If it doesn't matter if the slash is present, then I suggest changing this text: “XML-like tag syntax (with or without a space before the slash)” to something else.

  • Rob

    It would be useful if the documentation would give more information on specifying an owner document when adding newly created HTML.

  • http://bassistance.de/ Jörn Zaefferer

    The last variant, jQuery(), lacks any details.

  • http://twitter.com/josotoru Jose Soto Ruiz

    Ok, that example:

    jQuery(”,{
    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

  • http://twitter.com/josotoru Jose Soto Ruiz

    Ok, that example:

    jQuery(”,{
    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

    • http://teppicymon.myopenid.com/ Richard Green

      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”);

      • SiRiS

        The problem that I see is in the DIV tag ‘identifier’…

        Use this:
        jQuery (”,{..}).appendTo(‘body’);

        *Notice the self closing identifier.

        <{;o)~

    • http://twitter.com/aloon Alex G. Lacasa

      simply jQuery( html, props ) not work in IE8

  • Kecs

    What if there s more than one $(function(){…}), because of several linked script?

    • http://pikadudeno1.livejournal.com/ Pikadude No. 1

      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.

  • Yeikos

    var content = '<script>var x = 1;</'+'script>';
    $(content).find('script')[0]; // >> undefined

    why?

    • http://www.learningjquery.com/ Karl Swedberg

      …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

        • http://www.learningjquery.com/ Karl Swedberg

          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

  • http://twitter.com/bretto brett ohland

    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:
    $(”, {
    click: object.clickEvent,
    hover: (object.mouseOverEvent, object.mouseOutEvent)
    }).appendTo(containingDiv)

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

    Any ideas?

    • Emtucifor

      var x = (fn1, fn2);

      This is illegal syntax, and is what you're trying to assign to the hover property of the object.

      $('<div>')
      .click(object.clickEvent)
      .hover(object.mouseOverEvent, object.mouseOutEvent)
      .appendTo(containingDiv);

      Though, I could be missing some way that this is legal, it seems unlikely to me.</div>

    • http://www.tentonaxe.com Kevin

      the hover event is a short hand event that binds to both the mouseover and mouseout events. instead, you should be doing this:
      $('<div>', {
      click: object.clickEvent,
      mouseover: object.mouseOverEvent,
      mouseout: object.mouseOutEvent
      }).appendTo(containingDiv)</div>

  • http://www.professionalsofttech.com Tusharr_1987

    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?

  • 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?

    • Balee86

      i think that for attributes you have to use ” “, for events, only the name of event.

  • aina

    Hi all,
    Does anyone know how to create a new object with jQuery?
    And how about object inheritance?
    Thanks

  • Phi Khanh

    var html = “<ul><li>1</li><li>2</li></ul>”;
    var example = $(html, { “class”: “pk_slider_clicker” });

    doesn't work for me? IE said: “Object doesn't support this property or method”

    • Raul Castro

      try not to use the reserved word 'html'

    • http://waltersmith.us/ Walter Smith

      That form of $ only works when the first argument is a simple tag, like $('<ul>', {…}). Use $('…bunch of html…').attr({“class”: “pk_slider_clicker”}) instead.</ul>

  • Oipip

    ytutuu

  • Hola

    hola

  • http://twitter.com/wconcepts Colin Williams

    Are context searches more efficient/faster than those that traverse the entire DOM? Should context searches be used whenever possible for this reason?

  • Sam Bronson

    Wouldn't it be clearer if the documentation for the “jQuery( element )” form, and possibly the “jQuery( elementArray )” form, would be stated in terms of DOM nodes rather than elements? At least, that would make it much clearer that it's OK to pass in a Document node rather than an Element node.

    Also, I'm a bit puzzled as to why the first section covers all of these forms, which seems like a fairly mixed bag:

    * jQuery( selector, [ context ] )
    * jQuery( element )
    * jQuery( elementArray )
    * jQuery( jQuery object )
    * jQuery()

    I think it would make more sense to split out at least “jQuery( element )” and “jQuery( elementArray )”, and I'm not at all sure it wouldn't be good for each of the remaining forms to have a section to itself.

  • Fjanon

    What does jQuery return for $('div.foo') if there is no match? Empty array? How can we test there is a match or not?

    • http://www.learningjquery.com/ Karl Swedberg

      It returns an empty jQuery object (with length == 0). You can check the length property to see if there is a match.

    • chris

      it returns 'null', and testing for length will give a type error

      • Jonathan

        false

  • ThomasW

    Perhaps the '$' function — since it's the major part of the API — should be more primarily identified, in the documentation?

    It's taken me 15 minutes to find out it's not core JS syntax, to find out it's an alias for jQuery() function. Shouldn't it be in the 'Core' or 'Selection/ Traversal' section of the docs? If not all of these?

    • Foo Bar

      From the first sentence on this page: “In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM…”

  • http://twitter.com/johnmcmillion John McMillion

    Is there any way to pass the document context when doing a create element? If I have an iframe defined as follows..
    var f = window.frames.myIframe;
    How can I do this in jquery?
    var d = f.document.createElement(“div”);
    if I do $(“<div>”) it creates it on the parent frame document, not the iframe. This causes an invalid argument exception in IE 7 when doing a replaceChild().
    Please advise! Thanks!</div>

    • Info

      var myFrame=window.frames.myIframe;
      if(!myFrame.contentDocument) { myFrame.contentDocument=myFrame.contentWindow.document;
      }
      $('div',myFrame.contentDocument);

  • http://twitter.com/johnmcmillion John McMillion

    Is there any way to pass the document context when doing a create element? If I have an iframe defined as follows..
    var f = window.frames.myIframe;
    How can I do this in jquery?
    var d = f.document.createElement(“div”);
    if I do $(“<div>”) it creates it on the parent frame document, not the iframe. This causes an invalid argument exception in IE 7 when doing a replaceChild().
    Please advise! Thanks!</div>

  • Yshivambp

    jquery.schedule()
    any one use

  • Victor

    How can I work with DOM of child window document?

  • http://twitter.com/magicaj Adam Ayres

  • http://www.realestateanalysisfree.com/ Real Estate Analysis

    This works great. I am just redoing now all my older javascript files, because using the selectors this way – the code is just so much more readable. I love jQuery!

  • http://www.facebook.com/iulian.manea Iulian Manea

    hehe

  • Palini

    I dnt know wat u saying man!!!