jQuery DOM节点操作

一、创建节点

var box = $('<div id =box>节点</div>');  //创建一个节点

$('body').appended(box);      //将节点插入<body>元素内部

二、插入节点

内部插入节点方法

append(content)            向指定元素后面插入节点content

append(function (index,hml) {})    使用匿名函数向指定元素后面插入节点content(html是原节点)

appendTo(content)        将指定元素移入到指定元素content内部后面

prepend(content)           向指定元素前面插入节点content

prepend(function (index,html) {})  使用匿名函数向指定元素前面插入节点content

prependTo(content)          将指定元素移入到指定元素content内部前面

外部插入节点方法

after(content)向指定元素的外部后面插入节点content

after(function(index,html) {}) 使用匿名函数向指定元素的外部插入节点content

before(content)向指定元素外部前面插入节点content

before(function(index,html) {})使用匿名函数向指定元素前面插入节点content

insertAfter(content)将指定节点移到指定节点元素content外部后面

insertBefore(content)将指定节点移到指定节点元素content外部前面

三、包裹节点

wrap(html)          向指定元素包裹一层html代码

wrap(element)        向指定元素包裹一层DOM对象节点 $('div').wrap(document.createElement('strong'));

wrap(function (index) {})    使用匿名函数向指定元素包裹一层自定义内容

unwrap()             移除一层指定元素包裹的内容

wrapAll(html)         用html讲所有元素包裹到一起

wrapAll(element)        用DOM对象将所有元素包裹在一起

wrapInner(html)        向指定元素的子内容包裹一层html

wrapInner(elelment)      向指定元素的子内容包裹一层DOM对象节点

wrapInner(function (index) {})  用匿名函数向指定元素的子内容包裹一层

四、节点操作

//复制节点

$('body').append($('div').clone(ture)); //复制一个节点添加到HTML中

clone(true)参数可以为空表示只复制元素和内容,不复制事件行为。而加上true就可以复制事件行为。

//删除节点

$('div').remove();  //直接删除div元素

remove()不带参数时,删除前面指定元素。也可以带选择符参数,如$('div')remove('#box'),只删除id=box的div。

//保留事件的删除节点

$('div').detach();  //保留事件行为的删除

删除后本身方法可以返回当前被删除的节点对象。

//清空节点

$('div').empty();  //删除节点里的内容。

//替换节点

$('div').replaceWith('<span>节点</span>‘);  //将div替换成span元素

$('<span>节点</span>').replaceAll('div');  //同上

节点被替换后,所包含的事件行为就全部消失。

原文地址:https://www.cnblogs.com/IceSnova/p/7125500.html