jQuery Core - jQuery() Method

Instance

Find all p elements that are children of div elements and then set their border property:

$("div > p").css("border", "1px solid gray");

Try It Yourself

Definition and Usage

The jQuery() method accepts a string that contains a CSS selector used to match a set of elements.

The jQuery() function has three syntaxes:

Syntax 1

Accept a string that contains a CSS selector used to match a set of elements:

jQuery(selector, [context]

Detailed Usage

Syntax 2

Create DOM elements using strings with original HTML:

jQuery(html,ownerDocument]

Detailed Usage

Syntax 3

Bind a function to be executed after the DOM document is loaded:

jQuery(callback)

Detailed Usage

jQuery( selector, [ context ] )

This syntax has the following uses:

Usage 1: Set the selector environment

Syntax

jQuery(selector, [context]

By default, the selector searches the DOM from the root of the document. However, an optional context parameter can be set for $().

For example, if we want to search for an element in a callback, we can limit the following search:

Instance

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

Since we have limited the span selector to this environment, only the span in the clicked element will receive the additional class.

Internally, the selector environment is implemented through the .find() method, so $("span", this) is equivalent to $(this).find("span").

All core functions of jQuery are implemented through this function. Everything in jQuery is based on this function, or is using this function in some way. The most basic usage of this function is to pass an expression (usually composed of CSS selectors) to it, and then find all matching elements according to this expression.

By default, if the context parameter is not specified, $() will search for DOM elements in the current HTML document; if the context parameter is specified, such as a set of DOM elements or a jQuery object, it will search within that context. Since jQuery 1.3.2, the order of the returned elements is equivalent to the order of appearance in the context.

Usage 2: Use DOM element

Syntax

jQuery(element)

This function allows us to create a jQuery object by using a DOM element found in other ways. The usual usage of this feature is to call jQuery's methods on the element that has already been passed to the callback function through the this keyword:

Instance

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

This example uses a sliding animation to hide the element when it is clicked. Since the handler accepts the clicked item in the this keyword as a pure DOM element, it must be wrapped with a jQuery object before calling jQuery's methods on it.

This function can also accept XML documents and Window objects (although they are not DOM elements) as valid parameters.

After XML data is returned from an Ajax call, we can use the $() function to wrap the data with a jQuery object. Once done, we can use .find() and other DOM traversal methods to retrieve individual elements from the XML structure.

Usage 3: Clone jQuery object

Syntax

jQuery(jQuery object)

When a jQuery object is passed to the $() function in the form of a parameter, a copy of the object is created. Like the initial object, the new jQuery object references the same DOM element.

Usage 4: Return an empty collection

Syntax

jQuery()

For jQuery 1.4, calling the jQuery() method without parameters returns an empty jQuery collection. In previous versions of jQuery, this would return a collection containing the document node.

jQuery( html, [ ownerDocument ] )

This syntax has the following uses:

Usage 1: Create new elements

Syntax

jQuery(html,ownerDocument]

You can pass a manually written HTML string, or a string created by some template engine or plugin, or a string loaded via AJAX. However, there are limitations when creating input elements, which can be referred to in the second example.

Of course, this string can contain slashes (such as an image address) and backslashes. When creating a single element, please use closed tags or XHTML format. For example, to create a span, you can use $("<span/>") or $("<span></span>"), but $("<span>") is not recommended. In jQuery, this syntax is equivalent to $(document.createElement("span")).

If a string is passed as a parameter to $(), jQuery will check if the string is HTML (for example, if there are tags at certain positions in the string). If not, it will interpret the string as a selector expression, as explained above. However, if the string is an HTML fragment, jQuery will try to create the DOM elements described by the HTML fragment. Then it will create and return a jQuery object that references these DOM elements:

Instance

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

If an HTML fragment is more complex than a simple tag without attributes, like the HTML in the above example, then the actual creation process of the element is completed by the browser's innerHTML mechanism. Specifically, jQuery will create a new <div> element and then set the innerHTML attribute of the element to the passed HTML fragment. When the parameter is just a simple tag, such as $("<img />") or $("<a></a>"), jQuery will create the element by using the built-in JavaScript createElement() function.

To ensure cross-platform compatibility, the structure of the fragment must be good. Tags that can contain other elements must appear in pairs (with closing tags):

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

However, jQuery also allows a tag syntax similar to XML:

$("<a/>");

Tags that cannot contain other elements can be closed or not closed:

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

Usage 2: Set attributes and events

Syntax

jQuery(html,props)

For jQuery 1.4, we can pass an attribute mapping to the second parameter. This parameter accepts a superset of attributes that can be passed to the .attr() method. In addition, you can pass any event type and can call the following jQuery methods: val, css, html, text, data, width, height, or offset.

Note that Internet Explorer does not allow you to create an input element and change its type; you must use, for example, "<input type="checkbox" />" to specify the type.

Instance

Create an <input> element while setting the type attribute, attribute values, and some events.

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

jQuery(callback)

Allows you to bind a function to be executed after the DOM document is loaded.

This function acts like $(document).ready(), but when using this function, you need to wrap all other $() operations that need to be executed when the DOM is loaded into it. Although technically this function is chainable, there are not many cases where it is actually chained in this way.

Example

Execute the function within it after the DOM is loaded:

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