Created
July 17, 2014 09:00
-
-
Save hehongwei44/7614a218810410b31ff4 to your computer and use it in GitHub Desktop.
通过原型拓展来实现DOM的查找方法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//查找相关元素的前一个兄弟元素的方法。 | |
HTMLElement.prototype.prev = function () { | |
var elem = this; | |
do { | |
elem = elem.previousSibling; | |
} while (elem && elem.nodeType != 1); | |
return elem; | |
}; | |
//查找相关元素的下一个兄弟元素的方法。 | |
HTMLElement.prototype.next = function () { | |
var elem = this; | |
do { | |
elem = elem.nextSibling; | |
} while (elem && elem.nodeType != 1); | |
return elem; | |
}; | |
//查找元素第一个子元素的方法。 | |
HTMLElement.prototype.first = function () { | |
var elem = this.firstChild; | |
//文本节点 | |
if(elem && elem.nodeType != 1){ | |
do { | |
elem = elem.nextSibling; | |
} while (elem && elem.nodeType != 1); | |
} | |
return elem; | |
}; | |
//查找元素的最后一个子元素的方法。 | |
HTMLElement.prototype.last = function () { | |
var elem = this.lastChild; | |
do { | |
elem = elem.previousSibling; | |
} while (elem && elem.nodeType != 1); | |
return elem; | |
}; | |
//查找元素指定层级的父元素。 | |
HTMLElement.prototype.parent = function (num){ | |
var elem = this; | |
num = num || 1; | |
for( var i = 0; i < num; i++) | |
if(elem != null) elem = elem.parentNode; | |
return elem; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
HTML8之前的浏览器不支持HTMLElement,
可由其他的库来实现。http://www.browserland.org/scripts/htmlelement/