插入节点的方法: append()/appendTo()、prepend()/prependTo()、after()/insertAfter()、before/insertBefore()
这些插入节点的方法不仅能将新创建的DOM元素插入到文档中,也能对原有的DOM元素进行移动(若对已在文档中存在的元素使用插入节点的方法则相当于执行“移动节点”的操作)
实例↓
实现效果: 点击测试按钮,将所有.test标签里面的内容都移到该标签外面并删除所有的.test标签
无标题文档*{margin:0;padding:0;}
ul li{ list-style:none;}
img {border:0 none;}
body {padding:100px;}
input[type='button']{width:100px; height:38px;display:block;position:fixed;right:20%; top:50px;}
p{color:#f00;}
div{ color:#000; border:1px blue solid;}
div span{ display:block;}
$(function(){
$("input[type='button']").focus().click(function(){
$(".test >span").each(function(index, element) {
$(this).insertAfter($(this).parent()).prev().remove();
});
})
})
提示:你可以先修改部分代码再运行。
当然也可以直接使用replaceWith()方法来实现上面的替换效果
无标题文档*{margin:0;padding:0;}
ul li{ list-style:none;}
img {border:0 none;}
body {padding:100px;}
input[type='button']{width:100px; height:38px;display:block;position:fixed;right:20%; top:50px;}
p{color:#f00;}
div{ color:#000; border:1px blue solid;}
div span{ display:block;}
$(function(){
$("input[type='button']").focus().click(function(){
$(".test >span").each(function(index, element) {
var this_html=$(this).parent().html();
$(this).parent().replaceWith(this_html)
});
})
})
提示:你可以先修改部分代码再运行。