jQuery in Action
Setting element content
77
To empty
DOM
elements of their contents, we can use the
empty()
command.
Its syntax is as follows:
A common idiom is to use the
remove()
and
after()
commands to effect a
replacement operation. Consider the following:
$("div.elementToReplace").after("<p>I am replacing the div</p>").remove();
Because the
after()
function returns the original wrapped set containing the
<div>
, we can then remove it, resulting in a replacement of the original
<div>
with
the newly created
<p>
element.
If this is an idiom that you'll find yourself using over and over again,
remember that you can always wrap up such useful statements as extensions to
jQuery with
jQuery with
$.fn.replaceWith = function(html) {
return this.after(html).remove();
};
Its usage, to perform the same operation as shown in the previous example, is
$("div.elementToReplace").replaceWith("<p>I am replacing the div</p>");
Here, we see another example of creating extensions to jQuery. It's important
when doing so to return the wrapped set so that the chain can be continued after
it has been called (unless the purpose of the extension is to return other data).
You should be getting the hang of extending jQuery, but don't worry if you aren't;
it'll get fuller treatment later in this book (in chapter 7, to be exact).
when doing so to return the wrapped set so that the chain can be continued after
it has been called (unless the purpose of the extension is to return other data).
You should be getting the hang of extending jQuery, but don't worry if you aren't;
it'll get fuller treatment later in this book (in chapter 7, to be exact).
Sometimes, we don't want to move elements, but to copy them...
Command syntax: empty
empty()
Removes the content of all DOM elements in the matched set
Parameters
none
Returns
The wrapped set
The wrapped set