Примеры для jQuery .replaceWith()


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
25
26
27
28
29
30
31
32
33
34
35
36
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>replaceWith demo</title>
<style>
button {
display: block;
margin: 3px;
color: red;
width: 200px;
}
div {
color: red;
border: 2px solid blue;
width: 200px;
margin: 3px;
text-align: center;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button>First</button>
<button>Second</button>
<button>Third</button>
<script>
$( "button" ).click(function() {
$( this ).replaceWith( "<div>" + $( this ).text() + "</div>" );
});
</script>
</body>
</html>

Демонстрация:

Replace all paragraphs with bold words.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>replaceWith demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script>
$( "p" ).replaceWith( "<b>Paragraph. </b>" );
</script>
</body>
</html>

Демонстрация:

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
26
27
28
29
30
31
32
33
34
35
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>replaceWith demo</title>
<style>
div {
border: 2px solid blue;
color: red;
margin: 3px;
}
p {
border: 2px solid red;
color: blue;
margin: 3px;
cursor: pointer;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<div>Replaced!</div>
<script>
$( "p" ).click(function() {
$( this ).replaceWith( $( "div" ) );
});
</script>
</body>
</html>

Демонстрация:

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
33
34
35
36
37
38
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>replaceWith demo</title>
<style>
.container {
background-color: #991;
}
.inner {
color: #911;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p>
<button>Replace!</button>
</p>
<div class="container">
<div class="inner">Scooby</div>
<div class="inner">Dooby</div>
<div class="inner">Doo</div>
</div>
<script>
$( "button" ).on( "click", function() {
var $container = $( "div.container" ).replaceWith(function() {
return $( this ).contents();
});
$( "p" ).append( $container.attr( "class" ) );
});
</script>
</body>
</html>

Демонстрация: