You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/using-jquery-core/jquery-object.md
+31-30Lines changed: 31 additions & 30 deletions
Original file line number
Diff line number
Diff line change
@@ -4,41 +4,42 @@ title : The jQuery Object
4
4
attribution: Mike Pennisi
5
5
github : jugglinmike
6
6
---
7
-
Presumably, if you're reading this, you are curious about the thing that jQuery returns when you create new elements (or select existing ones).
8
-
This curiosity is a great first step, because at first glance, the jQuery object may seem to be an array of DOM elements.
9
-
It has a collection of DOM elements, some familiar array functions, and a `length` property, after all.
7
+
When creating new elements (or selecting existing ones), jQuery returns the elements in a collection.
8
+
Many developers new to jQuery assume that this collection is an array.
9
+
It has a zero-indexed sequence of DOM elements, some familiar array functions, and a `length` property, after all.
10
10
Actually, the jQuery object is more complicated than that.
11
11
12
12
### What is a DOM element? What is the DOM, for that matter?
13
13
14
14
The DOM (short for Document Object Model) is a representation of an HTML document.
15
15
It may contain any number of DOM elements.
16
-
At a high level, you can think a DOM element as a "piece" of a web page. It can contain text and/or other DOM elements.
16
+
At a high level, a DOM element can be thought of as a "piece" of a web page.
17
+
It may contain text and/or other DOM elements.
17
18
It is described by a type (i.e. "div", "a", "p", etc.) and any number of attributes (i.e. "src", "href", "class", etc.).
18
19
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).
19
20
20
21
Elements have properties like any JavaScript object.
21
22
Among these properties are attributes like `tagName` and methods like `appendChild`.
22
23
These properties are the only way to interact with the web page via JavaScript.
23
24
24
-
### So why not just put the elements in an array?
25
+
### Why not just put the elements in an array?
25
26
26
27
It turns out that working directly with DOM elements can be quite awkward.
27
28
The jQuery object defines [a ton](http://api.jquery.com/) of methods to smooth out the experience for developers.
28
29
For example:
29
30
30
-
*Compatability*
31
+
*Compatibility*
31
32
The implementation of element methods varies across browser vendors and versions.
32
-
Imagine that you wanted to set the inner HTML of a `tr` element stored in `target`. You might write:
33
+
The following snippet attempts to set the inner HTML of a `tr` element stored in `target`:
33
34
34
35
<javascriptcaption="Setting the inner HTML with the native DOM API">
This works in most cases, but it will fail in most versions of Internet Explorer.
40
+
This works in many cases, but it will fail in most versions of Internet Explorer.
40
41
In that case, the [recommended approach](http://www.quirksmode.org/dom/w3c_html.html) is to use pure DOM methods instead.
41
-
By wrapping the `target` element in a jQuery object, these edge cases are taken care of, and the expected result is acheived in all supported browsers:
42
+
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:
42
43
43
44
<javascriptcaption="Setting the inner HTML with jQuery">
By wrapping the `target` element in a jQuery object, you can accomplish the same task in a much simpler manner:
59
+
By wrapping the `target` element in a jQuery object, the same task becomes much simpler:
59
60
60
61
<javascriptcaption="Inserting a new element after another with jQuery">
61
62
var target = document.getElementById("target");
62
63
var newElement = document.createElement("div");
63
64
$( target ).after( newElement );
64
65
</javascript>
65
66
66
-
If you're in the business of getting things done (and I suspect that you are), then these details are simply "gotchas" that stand between you and your goals.
67
+
For the most part, these details are simply "gotchas" standing between a developer and her goals.
67
68
68
-
### Sounds good. Now how do I get stuff in there?
69
+
### Getting stuff in there
69
70
70
-
If you pass a CSS selector to the jQuery function, the result will be a jQuery object wrapping any element(s) that match this selector.
71
+
When the jQuery function is invoked with a CSS selector, it will return a jQuery object wrapping any element(s) that match this selector.
71
72
For instance, by writing
72
73
73
74
<javascriptcaption="Selecting all 'h1' tags">
74
75
var allHeaders = $("h1");
75
76
</javascript>
76
77
77
78
`headers` is now a jQuery element containing *all* the `<h1>` tags already on the page.
78
-
You can convince yourself by checking the `length` property of `headers`:
79
+
This can be verified by inspecting the `length` property of `headers`:
79
80
80
81
<javascriptcaption="Viewing the number of 'h1' tags on the page">
81
82
var allHeaders = $("h1");
@@ -84,34 +85,34 @@ alert( allHeaders.length );
84
85
85
86
If the page has more than one `<h1>` tag, this number will be greater than one.
86
87
Likewise, if the page has no `<h1>` tags, the `length` property will be zero.
87
-
Checking the `length` property is a common way to ensure that the selector described something on the page.
88
+
Checking the `length` property is a common way to ensure that the selector successfully matched one or more elements.
88
89
89
-
To make sure we only have the first header element, we have to take one more step.
90
+
If the goal is to select only the first header element, another step is required.
90
91
There are a number of ways to accomplish this, the most straight-forward may be the `eq()` function.
91
92
92
93
<javascriptcaption="Selecting only the first 'h1' element on the page (in a jQuery object)">
93
94
var headers = $("h1");
94
95
var firstHeader = headers.eq(0);
95
96
</javascript>
96
97
97
-
Now we can be assured that `firstHeader` is a jQuery object containing only the first `<h1>` element on the page.
98
-
And because `firstHeader` is a jQuery object, you can use methods like `html()`or`after()`.
98
+
Now `firstHeader` is a jQuery object containing only the first `<h1>` element on the page.
99
+
And because `firstHeader` is a jQuery object, it has useful methods like `html()`and`after()`.
99
100
jQuery also has a method named `get()` which provides a related function.
100
101
Instead of returning a jQuery-wrapped DOM element, it returns the DOM element itself.
101
102
102
103
<javascriptcaption="Selecting only the first 'h1' element on the page">
103
104
var firstHeaderElem = $("h1").get(0);
104
105
</javascript>
105
106
106
-
You can also treat the jQuery object like a true JavaScript array and use brackets to retrieve the DOM element you want, like so:
107
+
Alternatively, because the jQuery object is "array-like", it supports array subscripting via brackets:
107
108
108
109
<javascriptcaption="Selecting only the first 'h1' element on the page (alternate approach)">
109
110
var firstHeaderElem = $("h1")[0];
110
111
</javascript>
111
112
112
113
In either case, `firstHeaderElem` contains the "native" DOM element.
113
114
This means it has DOM properties like `innerHTML` and methods like `appendChild()`, but *not* jQuery methods like `html()` or `after()`.
114
-
As discussed earlier, the element is more difficult to work with, but there are certain instances where you will need it.
115
+
As discussed earlier, the element is more difficult to work with, but there are certain instances that require it.
This code functions identically to the example above, but it is a little more clear to read.
162
163
163
-
However you choose to organize your code, it is very important to make the distinction between jQuery object and native DOM elements!
164
-
You cannot access native DOM methods and properties directly from a jQuery object, and vice versa.
165
-
**If you see error messages like, "event.target.closest is not a function"' or "TypeError: Object [object Object] has no method 'setAttribute'" you are likely making this common mistake and now have the knowledge to remedy it.**
164
+
Regardless of the naming convention used, it is very important to make the distinction between jQuery object and native DOM elements!
165
+
Native DOM methods and properties are not present on the jQuery object, and vice versa.
166
+
**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.**
166
167
167
168
### jQuery objects are not "live"
168
169
@@ -172,13 +173,13 @@ Given a jQuery object with all the paragraph elements on the page:
172
173
var allParagraphs = $("p");
173
174
</javascript>
174
175
175
-
...you might expect that the contents will grow and shrink over time as `<p>` elements are added and removed from the document.
176
+
...one might expect that the contents will grow and shrink over time as `<p>` elements are added and removed from the document.
176
177
This is how "nodelists" returned by the `getElementsByTagName` method work, after all.
177
178
178
179
jQuery objects do **not** behave in this manner.
179
-
The set of elements contained within a jQuery object will not change unless you modify it in your code.
180
+
The set of elements contained within a jQuery object will not change unless explicitly modified.
180
181
This means that the collection is not "live"--it does not automatically update as the document changes.
181
-
If you expect the document may have changed from when you created the jQuery object, then update your collection by creating a new one!
182
+
If the document may have changed since the creation the jQuery object, the collection should be updated by creating a new one!
182
183
It can be as easy as re-running the same selector:
183
184
184
185
<javascriptcaption="Updating the selection">
@@ -190,6 +191,6 @@ allParagraphs = $("p");
190
191
Although DOM elements provide all the functionality one needs to create interactive web pages, they can be a hassle to work with.
191
192
The jQuery object wraps these elements to smooth out this experience and make common tasks easy.
192
193
When creating or selecting elements with jQuery, the result will always be wrapped in a new jQuery object.
193
-
If you do need the native DOM elements, you can always use the `get()` method and/or array-style subscripting to get at them.
194
+
If the situation calls for the native DOM elements, they may be accessed through the `get()` method and/or array-style subscripting.
194
195
195
-
These dinstinctions may not be immediately obvious, but understanding them is an important step in fully utilizing jQuery as it was intended.
196
+
These distinctions may not be immediately obvious, but understanding them is an important step in fully utilizing jQuery as it was intended.
0 commit comments