jQuery针对于DOM操作的方法主要有:append、prepend、before、after、replaceWith,appendTo,prependTo,insertBefore、insertAfter、replaceAll
$('.inner').after('<p>helo</p>')
//after:即在当前节点后面插入一个兄弟节点
after:function () {
return this.doMainip(arguments,function(elem){
if(this.parentNode){
this.parentNode.insertBefore(elem,this.nextSibling)
}
})
}
//insertAfter和after一样,但语法不一样
$('<p>Test</p>').insertAfter('.inner')//即将对象插入到class为inner的节点之后
//before即在匹配元素的前面插入内容
before:function(){
return this.doMainip(arguments,function(elem){
if(this.parentNode){
this.parentNode.insertBefore(elem,this)
}
})
}
//append 在每个匹配元素里面的末尾处插入参数内容
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
//prepend是将元素插入到每个匹配元素的前面
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
}
关于原生操作DOM的接口主要有appendChild()–通过把一个节点增加到当前节点的childNodes[]组,给文档树增加节点。
cloneNode() —复制当前节点,或者复制当前节点以及它的所有子孙节点
hasChildNodes()—如果当前节点拥有子节点,则将返回true。
insertBefore()—-给文档树插入一个节点,位置在当前节点的指定子节点之前。如果该节点已经存在,则删除之再插入到它的位置。
removeChild()— 从文档树中删除并返回指定的子节点。
replaceChild()—-从文档树中删除并返回指定的子节点,用另一个节点替换它。
同时对于遍历DOM节点:
parentNode():遍历到当前节点的父节点;
firstChild():遍历到当前节点的第一个子节点;
lastChild():遍历到当前节点的最后一个子节点;
nextSibling()遍历到当前节点的下一个同辈节点;
previousSibling()遍历到当前节点的上一个同辈节点;