Web Development with jQuery®

(Elliott) #1

Replacing Elements (^) ❘ 123


FIGURE 4-17


Replacing Elements


This section discusses two methods, jQuery’s replaceWith() and replaceAll(). The jQuery’s
replaceWith() method replaces a selection with whatever HTML content you specify. This works
similarly to jQuery’s html() method, but whereas the html() method sets an element’s contents,
jQuery’s replaceWith() method replaces the element and its content. This can be thought to be simi-
lar to Microsoft’s (now de facto standard) outerHTML property, for the portion of the outerHTML prop-
erty that can set or replace content.

The replaceAll() method is similar to the insertBefore() and insertAfter() methods that you
observed earlier in this chapter; it reverses the logic and is intended to be used with HTML content
already in the document, such as HTML you might reuse as a template.

The following document, Example 4-13, demonstrates how jQuery’s replaceWith() and repla-
ceAll() methods work:

<!DOCTYPE HTML>
<html lang='en'>
<head>
<meta http-equiv='X-UA-Compatible' content='IE=Edge' />
<meta charset='utf-8' />

http://www.it-ebooks.info

Free download pdf