协助实现我自己的getElementByID()

时间:2013-01-25 09:03:23

标签: javascript

我正在尝试在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 个答案:

答案 0 :(得分:2)

方法1:

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

方法2:

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;
}

答案 1 :(得分: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;
}

答案 2 :(得分:1)

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

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

第二个为什么迭代dom的所有元素?原生功能要快得多。

答案 3 :(得分:0)

使用BFS按ID方法自定义get元素:

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;
}