2013-01-25 69 views
0

我想在Javascript中實現我自己的getElementById()函數。我的想法/算法是這樣的:幫助實現我自己的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; 
     } 
    } 
} 
+3

你爲什麼要實現自己的版本?原生的有什麼問題? –

+0

你不喜歡JQuery選擇器? http://api.jquery.com/category/selectors/ – sdespont

+2

你的目標是什麼? – karthick

回答

2

方法1:

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

方法2:

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

方法3:(新瀏覽器)

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

DONE!

好吧,嚴重:

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

第二個是有趣的... –

+0

我不想在瀏覽器JS範圍中使用ant本機方法。我正在努力獲取文檔元素,然後遍歷它們以匹配ID。 – axiomtheorem

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

首先,你必須處理的要素有孩子,叫myGetElemById(),並選擇返回還是不返回,取決於結果。像這樣

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

秒爲什麼迭代dom的所有元素?本地功能要快得多。

+0

我同意。這只是爲了理解各種瀏覽器,它們的性能和數據結構的各種實現。一些使用基於MAP的結構,一些使用TREE。所以我想通過嘗試找到一個甜蜜點來實現我自己的功能。儘管已有的JS功能沒有任何問題。 – axiomtheorem