jQuery-Wrapped DOM Elements
The primary technique for manipulating the DOM with jQuery is using jQuery-
wrapped DOM elements. Any DOM manipulation you do with jQuery starts with cre‐
ating a jQuery object that’s “wrapped around” a set of DOM elements (keep in mind
the set could be empty or have only one element in it).
The jQuery function (
$
or
jQuery
) creates a jQuery-wrapped set of DOM elements
(which we will simply be referring to as a “jQuery object” from here on out—just
remember that a jQuery object holds a set of DOM elements!). The jQuery function
is primarily called in one of two ways: with a CSS selector or with HTML.
Calling jQuery with a CSS selector returns a jQuery object matching that selector
(similar to what’s returned from
document.querySelectorAll
). For example, to get a
jQuery object that matches all
<p>
tags, simply do:
const
$paras
=
$
(
'p'
);
$paras
.
length
;
// number of paragraph tags matched
typeof
$paras
;
// "object"
$paras
instanceof
$
;
// true
$paras
instanceof
jQuery
;
// true
Calling jQuery with HTML, on the other hand, creates new DOM elements based on
the HTML you provide (similar to what happens when you set an element’s
innerHTML
property):
const
$newPara
=
$
(
'<p>Newly created paragraph...</p>'
);
You’ll notice that, in both of these examples, the variable we assign the jQuery object
to starts with a dollar sign. This is not necessary, but it is a good convention to follow.
It allows you to quickly recognize variables that are jQuery objects.
Manipulating Elements
Now that we have some jQuery objects, what can we do with them? jQuery makes it
very easy to add and remove content. The best way to work through these examples is
to load our sample HTML in a browser, and execute these examples on the console.
Be prepared to reload the file; we’ll be wantonly removing, adding, and modifying
content.
jQuery provides
text
and
html
methods that are rough equivalents of assigning to a
DOM element’s
textContent
and
innerHTML
properties. For example, to replace
every paragraph with the same text:
$
(
'p'
).
text
(
'ALL PARAGRAPHS REPLACED'
);
Likewise, we can use
html
to use HTML content:
jQuery-Wrapped DOM Elements | 277