Created
July 25, 2012 15:36
-
-
Save lifesinger/3176815 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// oldj:设 A = $("#id a"),B = $("#id .c a"),求 A - B。要求: | |
// 1、不能用 jQuery 等框架; | |
// 2、兼容 IE6 在内的各大浏览器; | |
// 3、尽可能高效; | |
// 4、尽可能简短。 | |
function getWanted() { | |
var root = document.getElementById('id') | |
var all = root.getElementsByTagName('*') | |
var slice = Array.prototype.slice | |
var ret = [] | |
for(var i = 0, len = all.length; i < len; i++) { | |
var node = all[i] | |
if (!hasClass(node, 'c')) { | |
ret = ret.concat(slice.call(node.getElementsByTagName('a'))) | |
} | |
} | |
// 还需要去重,不过不想折腾了,呵呵 | |
return ret | |
} | |
function hasClass(node, className) { | |
return (' ' + node.className + ' ').indexOf(' ' + className + ' ') > -1 | |
} |
@elementstorn 嗯,笔误了。这个是 5 分钟内写的,纯回复微博 ...
anyway, 感谢反馈。
第10行的星号应该是对的吧,我倒是觉得循环里面,应该获取子节点;而且hasClass为true的时候,应该在all里面剔除其下面的所有节点
上面的格式弄错了,重新再弄了一下。
lifesinger的主要代码是这样:
var all = root.getElementsByTagName('*')
var slice = Array.prototype.slice
var ret = []
for(var i = 0, len = all.length; i < len; i++) {
var node = all[i]
if (!hasClass(node, 'c')) {
ret = ret.concat(slice.call(node.getElementsByTagName('a')))
}
}
这个逻辑显然是错的,不信试试:
<div id="id">
<div>
<div class="c">
<a href="#">a1</a>
<a href="#">a2</a>
</div>
<a href="#">a3</a>
<a href="#">a4</a>
</div>
</div>
正确的应该是:
// oldj:设 A = $("#id a"),B = $("#id .c a"),求 A - B。要求:
// 1、不能用 jQuery 等框架;
// 2、兼容 IE6 在内的各大浏览器;
// 3、尽可能高效;
// 4、尽可能简短。
function getWanted() {
var root = document.getElementById('id');
var aa = Array.prototype.slice.call(root.getElementsByTagName('a'),0);
for(var i = aa.length-1; i >= 0; i--) {
if (check(aa[i].parentNode)) {
aa.splice(i,1);
}
}
return aa;
}
function check(e){
while(e && e.id!='id'){
if(hasClass(e, 'c')){
return true;
}
e=e.parentNode;
}
return false;
}
function hasClass(node, className) {
return (' ' + node.className + ' ').indexOf(' ' + className + ' ') > -1;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 10 应该是 var all = root.getElementsByTagName('a')