2014-01-07 67 views
2

我正在尋找類似document.getElementsByClassName()的方法,但僅用於屬性,這也意味着document.getElementsByAttributeValue("class", "testclass")將具有與document.getElementsByClassName("testclass")相同的輸出。HTML通過屬性值獲取元素JavaScript函數

,因爲你不能只添加這樣

document.getElementsByAttributeValue = function(){....}; 

的功能,因爲它爲document.getElementById("foo").getElementsByAttributeValue(...)工作,以及它不是那麼容易。

不用說,我不想要一個JQuery解決方案,因爲不需要一個巨大的函數庫。

回答

2

我創建和實現看起來像這樣的功能:

Node.prototype.getElementsByAttributeValue = function(attribute, value){ 
    var dom = this.all || this.getElementsByTagName("*"); 
    var match = new Array(); 
    for (var i in dom) { 
     if ((typeof dom[i]) === "object"){ 
      if (dom[i].getAttribute(attribute) === value){ 
       match.push(dom[i]); 
      } 
     } 
    } 
    return match; 
}; 

我想每個HTML元素中,並在HTML文檔中以及工作中的作用,所以我增加了功能,父類的所有的html子類,Node類。

有一個不錯的可視化JavaScript objects

With this.all || this.getElementsByTagName("*")我把對象中的所有html元素都稱爲函數。然後,我經歷的所有元素循環我拿了,並檢查他們是否有正確的屬性值,如果他們有,我將他們推入match陣列

+4

沒有必要。你可以做'document.querySelectorAll(「* [foo ='bar']」)'或者替代'getElementsByClassName',它將是'document.querySelectorAll(「。some_class」)'。 – 2014-09-27 13:50:19

-4

您可以使用JQuery的輕鬆搞定所有與特定類的元素如下:

$('[class~="d1"]') 

這將選擇與含有類元素d1

檢查Demo

更多信息:請閱讀JQuery selector

+0

我想知道爲什麼我寫道我不想要任何jQuery – frieder

相關問題