2013-06-02 49 views
0

我正在開發一個項目,需要在頁面上查找特殊標記,然後獲取其屬性。標籤的例子看起來是這樣的:搜索沒有JQuery的特殊html標記的DOM

<ub:widget tag1="abc" tag2="doeraeme"></ub:widget:> 

無JQuery的,我怎麼可以使用JavaScript搜索每個UB:小部件,然後逐一收集他們的屬性?

+1

是'querySelectorAll()'選項嗎? https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll – BenM

回答

1

使用getElementsByTagName然後getAttribute

window.onload = function() { 
    var elements = document.getElementsByTagName("ub:widget"); 
    for (var i = 0; i < elements.length; i++) { 
     var widget = elements[i]; 
     var tag1 = widget.getAttribute("tag1"); 
     var tag2 = widget.getAttribute("tag2"); 
     alert("Found a widget! tag1 is " + tag1 + " and tag2 is " + tag2); 
    } 
} 

Live test case

如果你需要更通用的,即沒有預定義變量名可以遍歷所有元素,尋找那些含有「:」在標籤名,這通常意味着「特殊標籤」:

window.onload = function() { 
    var elements = document.getElementsByTagName("*"); 
    for (var i = 0; i < elements.length; i++) { 
     var curElement = elements[i]; 
     var curTagName = curElement.tagName.toLowerCase(); 
     if (curTagName.indexOf(":") > 0) { 
      var widget = curElement; 
      var message = "Found a widget! Tag name is: " + curTagName; 
      if (widget.attributes.length === 0) { 
       message += " without any attributes"; 
      } else { 
       message += " with " + widget.attributes.length + " attributes: "; 
       for (var j = 0; j < widget.attributes.length; j++) { 
        var curAttribute = widget.attributes[j]; 
        message += "\n" + curAttribute.name + " = " + curAttribute.value; 
       } 
      } 
      alert(message); 
     } 
    } 
} 

用通用方法處理Updated fiddle