Skip to content
Closed
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
1afacaa
style conformance for about-jquery/how-jquery-works
Nov 7, 2012
a98b0bf
style conformance for javascript-101/getting-started
Nov 7, 2012
776c4aa
style conformance for javascript-101/syntax-basics
Nov 7, 2012
f7641f4
style conformance for javascript-101/running-code
Nov 7, 2012
87ce1f2
style conformance for javascript-101/types
Nov 8, 2012
74be2db
style conformance for javascript-101/operators
Nov 8, 2012
cc01ee8
style conformance for javascript-101/conditional-code
Nov 8, 2012
2b4cf16
found the section on truthy/falsy
Nov 8, 2012
70b2003
style conformance for javascript-101/loops
Nov 8, 2012
6b04bb6
style conformance for javascript-101/arrays
Nov 8, 2012
0d7b57e
adding links to objects/arrays sections
Nov 8, 2012
f97c941
style conformance for javascript-101/objects
Nov 8, 2012
47fda0e
style conformance for javascript-101/functions
Nov 8, 2012
e498797
style conformance for javascript-101/testing-type
Nov 8, 2012
f1c8aff
link to testing-type section
Nov 8, 2012
2254121
style conformance for javascript-101/this-keyword
Nov 8, 2012
2dfb23a
style conformance for javascript-101/scope
Nov 8, 2012
1cb18ad
style conformance for javascript-101/closures
Nov 8, 2012
4259929
horizontal scrolling issues
Nov 8, 2012
a709de1
consistency with —
Nov 8, 2012
adcbaeb
style conformance for using-jquery-core/dollar-object-vs-function
Nov 8, 2012
bbe819e
style conformance for using-jquery-core/document-ready
Nov 8, 2012
bc6b21c
style conformance for using-jquery-core/avoid-conflicts-other-libraries
Nov 8, 2012
24b91ce
style conformance for using-jquery-core/attributes
Nov 8, 2012
8989211
style conformance for using-jquery-core/selecting-elements
Nov 8, 2012
d8c1ff5
style conformance for using-jquery-core/working-with-selections
Nov 9, 2012
3f9e54a
style conformance for using-jquery-core/manipulating-elements
Nov 9, 2012
947dff6
style conformance for using-jquery-core/data-methods
Nov 9, 2012
b17307b
style conformance for using-jquery-core/utility-methods
Nov 9, 2012
40c11cf
style conformance for using-jquery-core/jquery-object
Nov 9, 2012
96f06d4
style conformance for using-jquery-core/traversing
Nov 9, 2012
a52fe58
style conformance for using-jquery-core/css-styling-dimensions
Nov 9, 2012
6256c9e
style conformance for using-jquery-core/iterating
Nov 9, 2012
8f96503
style conformance for using-jquery-core/understanding-index
Nov 9, 2012
e512536
deleting obsolete exercises.md page
Nov 9, 2012
d6d5dcb
Update config-sample to reflect local.* instead of dev.*
ajpiano Nov 9, 2012
4ae27eb
Upgrade to grunt-jquery-content 0.5.10, add grunt-check-modules to gr…
ajpiano Nov 9, 2012
495a7b0
README.md updates
ajpiano Nov 9, 2012
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
style conformance for using-jquery-core/jquery-object
  • Loading branch information
jorydotcom committed Nov 9, 2012
commit 40c11cfccdf6476e7c8324329d147503a9588ca4
104 changes: 28 additions & 76 deletions page/using-jquery-core/jquery-object.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,43 +2,27 @@
title : The jQuery Object
level : beginner
---
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection.
Many developers new to jQuery assume that this collection is an array.
It has a zero-indexed sequence of DOM elements, some familiar array functions, and a `length` property, after all.
Actually, the jQuery object is more complicated than that.
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection. Many developers new to jQuery assume that this collection is an array. It has a zero-indexed sequence of DOM elements, some familiar array functions, and a `.length` property, after all. Actually, the jQuery object is more complicated than that.

### What is a DOM element? What is the DOM, for that matter?
## DOM and DOM elements

The DOM (short for Document Object Model) is a representation of an HTML document.
It may contain any number of DOM elements.
At a high level, a DOM element can be thought of as a "piece" of a web page.
It may contain text and/or other DOM elements.
It is described by a type (i.e. "div", "a", "p", etc.) and any number of attributes (i.e. "src", "href", "class", etc.).
For a more thorough description, please refer to [the official specification from the W3C](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614).
The Document Object Model (DOM for short) is a representation of an HTML document. It may contain any number of DOM elements. At a high level, a DOM element can be thought of as a "piece" of a web page. It may contain text and/or other DOM elements. DOM elements are described by a type, such as `<div>`, `<a>`, or `<p>`, and any number of attributes such as `src`, `href`, `class` and so on. For a more thorough description, refer to [the official DOM specification from the W3C](http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614).

Elements have properties like any JavaScript object.
Among these properties are attributes like `tagName` and methods like `appendChild`.
These properties are the only way to interact with the web page via JavaScript.
Elements have properties like any JavaScript object. Among these properties are attributes like `tagName` and methods like `appendChild`. These properties are the only way to interact with the web page via JavaScript.

### Why not just put the elements in an array?
## The jQuery Object

It turns out that working directly with DOM elements can be quite awkward.
The jQuery object defines [a ton](http://api.jquery.com/) of methods to smooth out the experience for developers.
For example:
It turns out that working directly with DOM elements can be awkward. The jQuery object defines [many](http://api.jquery.com/) methods to smooth out the experience for developers. Some benefits of the jQuery Object include:

*Compatibility*
The implementation of element methods varies across browser vendors and versions.
The following snippet attempts to set the inner HTML of a `tr` element stored in `target`:
*Compatibility* &#8212; The implementation of element methods varies across browser vendors and versions. The following snippet attempts to set the inner HTML of a `<tr>` element stored in `target`:

```
var target = document.getElementById("target");

target.innerHTML = "<td>Hello <b>World</b>!</td>";
```

This works in many cases, but it will fail in most versions of Internet Explorer.
In that case, the [recommended approach](http://www.quirksmode.org/dom/w3c_html.html) is to use pure DOM methods instead.
By wrapping the `target` element in a jQuery object, these edge cases are taken care of, and the expected result is achieved in all supported browsers:
This works in many cases, but it will fail in most versions of Internet Explorer. In that case, the [recommended approach](http://www.quirksmode.org/dom/w3c_html.html) is to use pure DOM methods instead. By wrapping the `target` element in a jQuery object, these edge cases are taken care of, and the expected result is achieved in all supported browsers:

```
// Setting the inner HTML with jQuery
Expand All @@ -47,9 +31,7 @@ var target = document.getElementById("target");
$( target ).html("<td>Hello <b>World</b>!</td>");
```

*Convenience*
There are also a lot of common DOM manipulation use cases that are awkward to accomplish with pure DOM methods.
For instance, inserting an element stored in `newElement` after the `target` element requires a rather verbose DOM method:
*Convenience* &#8212; There are also a lot of common DOM manipulation use cases that are awkward to accomplish with pure DOM methods. For instance, inserting an element stored in `newElement` after the `target` element requires a rather verbose DOM method:

```
// Inserting a new element after another with the native DOM API
Expand All @@ -71,20 +53,18 @@ var newElement = document.createElement("div");
$( target ).after( newElement );
```

For the most part, these details are simply "gotchas" standing between a developer and her goals.
For the most part, these details are simply "gotchas" standing between you and your goals.

### Getting stuff in there
### Getting Elements in to the jQuery Object

When the jQuery function is invoked with a CSS selector, it will return a jQuery object wrapping any element(s) that match this selector.
For instance, by writing
When the jQuery function is invoked with a CSS selector, it will return a jQuery object wrapping any element(s) that match this selector. For instance, writing:

```
// Selecting all 'h1' tags
var headers = $("h1");
```

`headers` is now a jQuery element containing *all* the `h1` tags already on the page.
This can be verified by inspecting the `length` property of `headers`:
`headers` is now a jQuery element containing *all* the `<h1>` tags already on the page. This can be verified by inspecting the `length` property of `headers`:

```
// Viewing the number of 'h1' tags on the page
Expand All @@ -93,12 +73,9 @@ var allHeaders = $("h1");
alert( allHeaders.length );
```

If the page has more than one `h1` tag, this number will be greater than one.
Likewise, if the page has no `h1` tags, the `length` property will be zero.
Checking the `length` property is a common way to ensure that the selector successfully matched one or more elements.
If the page has more than one `<h1>` tag, this number will be greater than one. If the page has no `<h1>` tags, the `length` property will be zero. Checking the `length` property is a common way to ensure that the selector successfully matched one or more elements.

If the goal is to select only the first header element, another step is required.
There are a number of ways to accomplish this, the most straight-forward may be the `eq()` function.
If the goal is to select only the first header element, another step is required. There are a number of ways to accomplish this, but the most straight-forward is the `eq()` function.

```
// Selecting only the first 'h1' element on the page (in a jQuery object)
Expand All @@ -107,49 +84,40 @@ var headers = $("h1");
var firstHeader = headers.eq( 0 );
```

Now `firstHeader` is a jQuery object containing only the first `h1` element on the page.
And because `firstHeader` is a jQuery object, it has useful methods like `html()` and `after()`.
jQuery also has a method named `get()` which provides a related function.
Instead of returning a jQuery-wrapped DOM element, it returns the DOM element itself.
Now `firstHeader` is a jQuery object containing only the first `<h1>` element on the page. And because `firstHeader` is a jQuery object, it has useful methods like `.html()` and `.after()`. jQuery also has a method named `.get()` which provides a related function. Instead of returning a jQuery-wrapped DOM element, it returns the DOM element itself.

```
// Selecting only the first 'h1' element on the page
var firstHeaderElem = $("h1").get( 0 );
```

Alternatively, because the jQuery object is "array-like", it supports array subscripting via brackets:
Alternatively, because the jQuery object is "array-like," it supports array subscripting via brackets:

```
// Selecting only the first 'h1' element on the page (alternate approach)
var firstHeaderElem = $("h1")[ 0 ];
```

In either case, `firstHeaderElem` contains the "native" DOM element.
This means it has DOM properties like `innerHTML` and methods like `appendChild()`, but *not* jQuery methods like `html()` or `after()`.
As discussed earlier, the element is more difficult to work with, but there are certain instances that require it.
One such instance is making comparisons.
In either case, `firstHeaderElem` contains the native DOM element. This means it has DOM properties like `.innerHTML` and methods like `.appendChild()`, but *not* jQuery methods like `.html()` or `.after()`. The `firstHeaderElem` element is more difficult to work with, but there are certain instances that require it. One such instance is making comparisons.

### Not all jQuery objects are created `===`
### Not All jQuery Objects are Created `===`

An important detail regarding this "wrapping" behavior is that each wrapped object is unique.
This is true *even if the object was created with the same selector or contain references to the exact same DOM elements*.
An important detail regarding this "wrapping" behavior is that each wrapped object is unique. This is true *even if the object was created with the same selector or contain references to the exact same DOM elements*.

```
// Creating two jQuery objects for the same element
var logo1 = $("#logo");
var logo2 = $("#logo");
```

Although `logo1` and `logo2` are created in the same way (and wrap the same DOM element), they are not the same object.
For example:
Although `logo1` and `logo2` are created in the same way (and wrap the same DOM element), they are not the same object. For example:

```
// Comparing jQuery objects
alert( $("#logo") === $("#logo") ); // alerts 'false'
```

However, both objects contain the same DOM element.
The `get` method is useful for testing if two jQuery objects have the same DOM element.
However, both objects contain the same DOM element. The `get` method is useful for testing if two jQuery objects have the same DOM element.

```
// Comparing DOM elements
Expand All @@ -162,9 +130,7 @@ var logo2Elem = logo2.get( 0 );
alert( logo1Elem === logo2Elem ); // alerts 'true'
```

Many developers prefix a `$` to the name of variables that contain jQuery objects in order to help differentiate.
There is nothing magic about this practice--it just helps some people to keep track of what different variables contain.
The previous example could be re-written to follow this convention:
Many developers prefix a `$` to the name of variables that contain jQuery objects in order to help differentiate. There is nothing magic about this practice &#8212; it just helps some people keep track of what different variables contain. The previous example could be re-written to follow this convention:

```
// Comparing DOM elements (with more readable variable names)
Expand All @@ -179,11 +145,9 @@ alert( logo1 === logo2 ); // alerts 'true'

This code functions identically to the example above, but it is a little more clear to read.

Regardless of the naming convention used, it is very important to make the distinction between jQuery object and native DOM elements!
Native DOM methods and properties are not present on the jQuery object, and vice versa.
**Error messages like, "event.target.closest is not a function"' and "TypeError: Object [object Object] has no method 'setAttribute'" indicate the presence of this common mistake.**
Regardless of the naming convention used, it is very important to make the distinction between jQuery object and native DOM elements. Native DOM methods and properties are not present on the jQuery object, and vice versa. Error messages like "event.target.closest is not a function"' and "TypeError: Object [object Object] has no method 'setAttribute'" indicate the presence of this common mistake.

### jQuery objects are not "live"
### jQuery Objects Are Not "Live"

Given a jQuery object with all the paragraph elements on the page:

Expand All @@ -192,25 +156,13 @@ Given a jQuery object with all the paragraph elements on the page:
var allParagraphs = $("p");
```

...one might expect that the contents will grow and shrink over time as `<p>` elements are added and removed from the document.
This is how "NodeLists" returned by the `getElementsByTagName` method work, after all.

jQuery objects do **not** behave in this manner.
The set of elements contained within a jQuery object will not change unless explicitly modified.
This means that the collection is not "live"--it does not automatically update as the document changes.
If the document may have changed since the creation the jQuery object, the collection should be updated by creating a new one!
It can be as easy as re-running the same selector:
...one might expect that the contents will grow and shrink over time as `<p>` elements are added and removed from the document. jQuery objects do **not** behave in this manner. The set of elements contained within a jQuery object will not change unless explicitly modified. This means that the collection is not "live" &#8212; it does not automatically update as the document changes. If the document may have changed since the creation the jQuery object, the collection should be updated by creating a new one. It can be as easy as re-running the same selector:

```
// Updating the selection
allParagraphs = $("p");
```

### Wrapping up

Although DOM elements provide all the functionality one needs to create interactive web pages, they can be a hassle to work with.
The jQuery object wraps these elements to smooth out this experience and make common tasks easy.
When creating or selecting elements with jQuery, the result will always be wrapped in a new jQuery object.
If the situation calls for the native DOM elements, they may be accessed through the `get()` method and/or array-style subscripting.
### Wrapping Up

These distinctions may not be immediately obvious, but understanding them is an important step in fully utilizing jQuery as it was intended.
Although DOM elements provide all the functionality one needs to create interactive web pages, they can be a hassle to work with. The jQuery object wraps these elements to smooth out this experience and make common tasks easy. When creating or selecting elements with jQuery, the result will always be wrapped in a new jQuery object. If the situation calls for the native DOM elements, they may be accessed through the `.get()` method and/or array-style subscripting.