返回元素elem的第n层祖先元素
function retParent(elem,n) {
while(elem && n) {
elem = elem.parentElement;
n --;
}
return elem;
}
封装Haschildren功能,解决以前部分浏览器的兼容性问题
Element.prototype.mHasChildren = function () {
child = this.childNode,
len = child.length;
for(var i = 0; i < len; i++){
if(child[i].nodeType == 1){
return true;
}
}
return false;
}
封装函数,返回元素e的第n个兄弟节点,n为正,返回后面的兄弟节点,n为负,返回前面的,n为0,返回自己。
function retSibling(e,n) {
while(e && n) {
if(n > 0) {
if(e.nextElementSibling){
e = e.nextElementSibling;
}else{//兼容ie
for(e = e.nextSibling; e && e.nodeType != 1; e = e.nextSibling);
}
n --;
}else{
if(e.previousElementSibling){
e = e.previousElementSibling;
}else{//兼容ie
for(e = e.previousSibling; e && e.nodeType != 1; e = e.previousSibling);
n ++;
}
}
return e;
}
在原型链上封装insertAfter
Element.prototype.insertAfter = function(targetNode,afterNode) {
var beforeNode = afterNode.nextElementSibling;
if(beforeNode == null) {
this.appendChild(targetNode);
}else{
this.insertBefore(target,beforeNode);
}
}