如何用另一个元素替换一个元素

How to replace an element with another one?

本文关键字:元素 一个 替换 何用 另一个      更新时间:2023-09-26

>我有这个HTML结构:

<div>something</div>
<p>this is a paragraph</p>

现在我想用<span>替换该<p>。像这样的东西;

<div>something</div>
<span>this is a span</span>

我想要这样的东西:

$("div").siblings("p"). /* replace with "<span>this is a span</span>" */

注意:<p>周围没有任何包装器。所以我不能使用.html().


那么,这样做可以吗?

考虑到给定的html,你可以这样做:

$("div").next("p").replaceWith('<span>This is a span</span>'); 

你可以使用这个:

$('p').replaceWith(function(){
    return $("<span />", {html: $(this).html()});
});

见小提琴:http://jsfiddle.net/DIRTY_SMITH/k2swf/592/

jQuery .replaceWith() 方法从 DOM 中删除内容,并通过一次调用在其位置插入新内容。考虑这个 DOM 结构:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

第二个内部<div>可以替换为指定的 HTML:

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

这导致结构:

<div class="container">
  <div class="inner first">Hello</div>
  <h2>New heading</h2>
  <div class="inner third">Goodbye</div>
</div>

见 http://api.jquery.com/replacewith/