.replaceWith( newContent )Returns: jQuery
Description: Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
-
version added: 1.2.replaceWith( newContent )
-
newContentThe content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object.
-
-
version added: 1.4.replaceWith( function )
-
functionType: Function()A function that returns content with which to replace the set of matched elements.
-
.replaceWith()
method removes content from the DOM and inserts new content in its place with a single call. Consider this DOM structure:
1
2
3
4
5
|
|
<div>
could be replaced with the specified HTML:
1
|
|
1
2
3
4
5
|
|
<div>
elements could be targeted at once:
1
|
|
1
2
3
4
5
|
|
1
|
|
1
2
3
4
|
|
.replaceWith()
method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.
Additional Notes:
-
The
.replaceWith()
method removes all data and event handlers associated with the removed nodes. -
Prior to jQuery 1.9,
.replaceWith()
would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. The method might or might not have returned a new result depending on the number or connectedness of its arguments! As of jQuery 1.9,.after()
,.before()
, and.replaceWith()
always return the original unmodified set. Attempting to use these methods on a node without a parent has no effect—that is, neither the set nor the nodes it contains are changed.
Examples:
Example 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
|
Demo:
Example 2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
|
Demo:
Example 3
$()
function. Notice it doesn't clone the object but rather moves it to replace the paragraph.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
|
Demo:
Example 4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
|