0

我正在尝试在 Javascript 中实现我自己的 getElementById() 函数。我的想法/算法是这样的:

function myGetElemById(id){
    // rootNode I suppose will be the BODY tag.
    rootElem = get elements by TAGNAME (rootNode);
    elems = rootElems.getChildren();
    for(i=0; i<elems.length; i++){
        if(!elems[i].hasChildren()){
            myGetElemById(elems[i]);
        } else {
          if(elems[i].id == id)
              return elems[i];
          else
              return null;  
        }
    }
}
4

4 回答 4

2

方法一:

function myGetElemById(id){
  return document.getElementById(id);
}

方法二:

function myGetElemById(id){
  return window[id];
}

方法3:(较新的浏览器)

function myGetElemById(id){
  return document.querySelectorAll('#' + id);
}

完毕!

好吧,说真的:

function getById(id, parent, list){
  parent = parent || document.body;
  list   = list   || [];

  var l, child, children = parent.children;

  if(children){
    l = children.length;
    while(l--){
      child = children[l];
      if(child.id == id) list.push(child);
      getById(id, child, list);
    }
  }

  return list;
}
于 2013-01-25T09:09:51.030 回答
1

看看这个功能,也许你能得到想法

function getElementsStartsWithId( id ) {
  var children = document.body.getElementsByTagName('*');
  var elements = [], child;
  for (var i = 0, length = children.length; i < length; i++) {
    child = children[i];
    if (child.id.substr(0, id.length) == id)
      elements.push(child);
  }
  return elements;
}
于 2013-01-25T09:10:30.513 回答
1

首先,必须处理有子元素,调用 myGetElemById() 并选择返回或不返回,取决于结果。像这样

    ...
    if(!elems[i].hasChildren()){
        var result = myGetElemById(elems[i]);
        if (result != null)
            return result;
    } else {
    ...

其次,为什么要遍历 dom 的所有元素?本机功能要快得多。

于 2013-01-25T09:10:50.200 回答
0

使用 BFS 通过 ID 方法自定义获取元素:

function myGetElementById(id, root){
    let queue = [];  // Using array here but linkedList is more performant in both time and space complexity

    queue.push(root);

    let currentNode;

    while(queue.length){
        currentNode = queue.shift();
        if(currentNode.id === id){
            return currentNode;
        } 

        queue.push(...currentNode.children);
    }

    return false;
}
于 2018-03-28T23:15:42.107 回答