如何将一个html元素替换为另一个

时间:2014-01-26 02:09:03

标签: jquery

我正在尝试用jQuery替换div中的表单,请考虑使用html:

<div>
  <form>
    <input type="text" value="some text here" id="friendship" class="not_friends">
  </form>
</div>

并遵循js代码:

div = $("#friendship.not_friends").parent().parent();
$("form", div).remove();
$(div).add(response);

“form”元素被删除,如我所愿,但新形式(在'响应'字符串中)没有添加到div,为什么? 还有一种更好的方法来编写这个js代码?这看起来对我不好。

2 个答案:

答案 0 :(得分:3)

您需要使用.append() / .html()

$(div).append(response);

.add()返回一个新的jQuery对象,其中包含当前对象和传递的选择器返回的对象

答案 1 :(得分:3)

jQuery内置了将一个元素替换为另一个元素的功能。

请参阅:.replaceWith()

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

$("form").replaceWith(response);
相关问题