2011-10-04 178 views
27

JavaScript中有方法可用於獲取使用其ID,類和標記的HTML元素。按屬性名稱獲取HTML元素

document.getElementByID(*id*); 
document.getElementsByClassName(*class*); 
document.getElementsByTagName(*tag*); 

是否有任何方法可以根據屬性名稱獲取元素。

EX:

<span property="v:name">Basil Grilled Tomatoes and Onions</span> 

像:

document.getElementsByAttributeName("property"); 
+0

你能否解釋一下爲什麼你需要做的是專門這樣?這是非常低效的,並有更好的方法來處理它。 – 2011-10-04 16:44:38

回答

47

是的,但它不存在於所有的瀏覽器。舊版本的Internet Explorer(即版本8之前)不支持它。函數是querySelectorAll(或單個元素爲querySelector),它允許您使用CSS選擇器來查找元素。

document.querySelectorAll('[property]'); // All with attribute named "property" 
document.querySelectorAll('[property=value]'); // All with "property" set to "value" exactly. 

(Complete list of attribute selectors on MDN.)

此找到與特性屬性的所有元素。這將是最好指定標記名稱如果可能的話:

document.querySelectorAll('span[property]'); 

如有必要,您可以解決此通過網頁上的所有元素循環,看他們是否有該屬性設置:

var withProperty = [], 
    els = document.getElementsByTagName('span'), // or '*' for all types of element 
    i = 0; 

for (i = 0; i < els.length; i++) { 
    if (els[i].hasAttribute('property')) { 
     withProperty.push(els[i]); 
    } 
} 

像jQuery這樣的庫可以爲你處理這個問題:讓它們完成繁重的工作可能是一個好主意。

0

我想你想看看jQuery因爲這Javascript庫提供了很多的功能,你可能想在這樣的使用案例。你的情況,你可以寫(或者找到一個在互聯網上)一個hasAttribute方法,像這樣(未測試):

$.fn.hasAttribute = function(tagName, attrName){ 
    var result = []; 
    $.each($(tagName), function(index, value) { 
    var attr = $(this).attr(attrName); 
    if (typeof attr !== 'undefined' && attr !== false) 
     result.push($(this)); 
    }); 
    return result; 
} 
2

在jQuery中是這樣:

$("span['property'=v:name]"); // for selecting your span element 
-1

隨着prototypejs

$$('span[property=v.name]'); 

document.body.select('span[property=v.name]'); 

兩個返回陣列

+0

不適用於鉻14.0.835.187 m(Windows) –

1

只是另一個答案

Array.prototype.filter.call(
    document.getElementsByTagName('span'), 
    function(el) {return el.getAttribute('property') == 'v.name';} 
); 

在未來

Array.prototype.filter.call(
    document.getElementsByTagName('span'), 
    (el) => el.getAttribute('property') == 'v.name' 
)