Skip to content

Instantly share code, notes, and snippets.

@hehongwei44
Created July 17, 2014 09:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hehongwei44/7614a218810410b31ff4 to your computer and use it in GitHub Desktop.
通过原型拓展来实现DOM的查找方法。
//查找相关元素的前一个兄弟元素的方法。
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;
};
@hehongwei44
Copy link
Author

HTML8之前的浏览器不支持HTMLElement,
可由其他的库来实现。http://www.browserland.org/scripts/htmlelement/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment