« 2009年6月 | トップページ

2009年7月31日 (金)

指定したオブジェクトを取得

JQuery もどきの関数を書いてみました。

/***************************************************

    指定したオブジェクトを取得する

    #id, .class, それ以外はタグ名と看做す。
    id の場合はオブジェクトを、
    それ以外はオブジェクトの配列を返す。

 ***************************************************/
var $ = function(selector) {
  if (selector.charAt(0) == '#')
    return document.getElementById(selector.substring(1));
  else if (selector.charAt(0) == '.') {
    var elems = new Array();
    var all = document.getElementsByTagName('*');
    var re = new RegExp("\\b" + selector.substring(1) + "\\b");
    for (var i = 0; i < all.length; i++) {
      if (re.test(all[i].className))
        elems.push(all[i]);
    }
    return elems;
  }
  return document.getElementsByTagName(selector);
};

|

« 2009年6月 | トップページ