.replaceWith()


.replaceWith( newContent )Возвращает: jQuery

Описание: С помощью этой функции можно заменять элементы страницы новыми элементами или уже существующими.

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
<div class="container">
<div class="inner first">Hello</div>
<div class="inner second">And</div>
<div class="inner third">Goodbye</div>
</div>

The second inner <div> could be replaced with the specified HTML:

1
$( "div.second" ).replaceWith( "<h2>New heading</h2>" );

This results in the structure:

1
2
3
4
5
<div class="container">
<div class="inner first">Hello</div>
<h2>New heading</h2>
<div class="inner third">Goodbye</div>
</div>

All inner <div> elements could be targeted at once:

1
$( "div.inner" ).replaceWith( "<h2>New heading</h2>" );

This causes all of them to be replaced:

1
2
3
4
5
<div class="container">
<h2>New heading</h2>
<h2>New heading</h2>
<h2>New heading</h2>
</div>

An element could also be selected as the replacement:

1
$( "div.third" ).replaceWith( $( ".first" ) );

This results in the DOM structure:

1
2
3
4
<div class="container">
<div class="inner second">And</div>
<div class="inner first">Hello</div>
</div>

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.

Дополнительные замечания:

  • 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.

Примеры использования