Skip to content

Instantly share code, notes, and snippets.

@lifesinger
Created July 25, 2012 15:36
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 lifesinger/3176815 to your computer and use it in GitHub Desktop.
Save lifesinger/3176815 to your computer and use it in GitHub Desktop.
// 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
}
@elementstorm
Copy link

line 10 应该是 var all = root.getElementsByTagName('a')

@lifesinger
Copy link
Author

@elementstorn 嗯,笔误了。这个是 5 分钟内写的,纯回复微博 ...

anyway, 感谢反馈。

@xiaozi
Copy link

xiaozi commented Jul 27, 2012

第10行的星号应该是对的吧,我倒是觉得循环里面,应该获取子节点;而且hasClass为true的时候,应该在all里面剔除其下面的所有节点

@cuixiping
Copy link

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')))
}
}
这个逻辑显然是错的,不信试试:

@cuixiping
Copy link

上面的格式弄错了,重新再弄了一下。
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