Skip to content

Instantly share code, notes, and snippets.

@sofish
Last active October 20, 2015 13:09
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sofish/0c5f30608ef511281b7d to your computer and use it in GitHub Desktop.
Save sofish/0c5f30608ef511281b7d to your computer and use it in GitHub Desktop.
rewrite `parent` and `find` method for jqLite
angular.$ = angular.element;
// jqLite `.parent([selector])` 支持 selector
angular.$.prototype.parent = function(sel) {
if(!sel) return angular.$(this[0].parentNode);
var list = [].slice.call(document.querySelectorAll(sel))
, currentNode = this[0]
, ret;
while(currentNode.nodeName !== 'HTML') {
currentNode = currentNode.parentNode;
var index = list.indexOf(currentNode);
if(index !== -1) {
ret = currentNode;
currentNode = document.documentElement;
continue;
}
}
return angular.$(ret);
}
// jqLite `.find([selector])` 支持 selector
angular.$.prototype.find = function(sel) {
if(!sel) return angular.$();
var list = [].slice.call(document.querySelectorAll(sel))
, childrens = [].slice.call(this[0].getElementsByTagName('*'))
, ret = [];
list.forEach(function(el) {
if(childrens.indexOf(el) !== -1) ret.push(el);
})
return angular.$(ret);
}
@exherb
Copy link

exherb commented Jun 13, 2014

其实很少有这两个方法的需求,我还没遇到过

@sofish
Copy link
Author

sofish commented Jun 13, 2014

@exherb 写 UI 组件的时候会非常多用到。

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