.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, 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.
-
The .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
|
|
The second inner <div>
could be replaced with the specified HTML:
1
|
|
This results in the structure:
1
2
3
4
5
|
|
All inner <div>
elements could be targeted at once:
1
|
|
This causes all of them to be replaced:
1
2
3
4
5
|
|
An element could also be selected as the replacement:
1
|
|
This results in the DOM structure:
1
2
3
4
|
|
This example demonstrates that the selected element replaces the target by being moved from its old location, not by being cloned.
The .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.
As of jQuery 1.4, .replaceWith()
can also work on disconnected DOM nodes. For example, with the following code, .replaceWith()
returns a jQuery set containing only a paragraph.:
1
|
|
The .replaceWith()
method can also take a function as its argument:
1
2
3
|
|
This results in <div class="container">
being replaced by its three child <div>
s. The return value of the function may be an HTML string, DOM element, or jQuery object.
Examples:
Example: On click, replace the button with a div containing the same word.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
|
Example: Replace all paragraphs with bold words.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
|
Example: On click, replace each paragraph with a div that is already in the DOM and selected with the $()
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
|
|
Example: On button click, replace the containing div with its child divs and append the class name of the selected element to 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
|
|