javascript - 在 querySelectorAll 不可用且不使用函式庫的情況下,如何透過屬性取得元素?
<p data-foo="bar">
你如何做到相當於
document.querySelectorAll('[data-foo]')
querySelectorAll 不可用的地方?
我需要一個至少能在 IE7 運作的原生解決方案。我不在乎 IE6。
答案#1
你可以編寫一個函數,運行 getElementsByTagName('*'),並僅返回具有“data-foo”屬性的那些元素:
function getAllElementsWithAttribute(attribute)
{
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++)
{
if (allElements[i].getAttribute(attribute) !== null)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
}
然後,
getAllElementsWithAttribute('data-foo');
答案#2
使用
//find first element with "someAttr" attribute
document.querySelector('[someAttr]')
或
//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]')
通過屬性查找元素。現在所有相關瀏覽器都支持(即使是 IE8):http://caniuse.com/#search=queryselector
答案#3
我稍微試了一下,最後得到這個粗糙的解決方案:
function getElementsByAttribute(attribute, context) {
var nodeList = (context || document).getElementsByTagName('*');
var nodeArray = [];
var iterator = 0;
var node = null;
while (node = nodeList[iterator++]) {
if (node.hasAttribute(attribute)) nodeArray.push(node);
}
return nodeArray;
}
使用方法非常簡單,即使在 IE8 中也能運作:
getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);
http://fiddle.jshell.net/9xaxf6jr/
但我建議使用querySelector/All來做到這一點(並且為了支持舊瀏覽器,可以使用 polyfill):
document.querySelectorAll('[data-foo]');
答案#4
試試這個,它有效
document.querySelector('[attribute="value"]')
範例:
document.querySelector('[role="button"]')
