rya*_*nve 120 javascript dom
<p data-foo="bar">
Run Code Online (Sandbox Code Playgroud)
你怎么能做相同的
document.querySelectorAll('[data-foo]')
Run Code Online (Sandbox Code Playgroud)
我需要一个至少在IE7中工作的本机解决方案.我不关心IE6.
小智 130
您可以编写一个运行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;
}
Run Code Online (Sandbox Code Playgroud)
然后,
getAllElementsWithAttribute('data-foo');
Run Code Online (Sandbox Code Playgroud)
Pyl*_*nux 57
使用
//find first element with "someAttr" attribute
document.querySelector('[someAttr]')
Run Code Online (Sandbox Code Playgroud)
要么
//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]')
Run Code Online (Sandbox Code Playgroud)
按属性查找元素.现在所有相关浏览器(甚至是IE8)都支持它:http://caniuse.com/#search=queryselector
yck*_*art 44
我玩了一下,结束了这个粗糙的解决方案:
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;
}
Run Code Online (Sandbox Code Playgroud)
用法非常简单,甚至可以在IE8中使用:
getElementsByAttribute('data-foo');
// or with parentNode
getElementsByAttribute('data-foo', document);
Run Code Online (Sandbox Code Playgroud)
http://fiddle.jshell.net/9xaxf6jr/
但我建议使用querySelector
/ All
为此(并支持旧浏览器使用polyfill):
document.querySelectorAll('[data-foo]');
Run Code Online (Sandbox Code Playgroud)
试试这个有效
document.querySelector( '[属性= "值"]')
例如:
document.querySelector('[role="button"]')
Run Code Online (Sandbox Code Playgroud)
这也可行:
document.querySelector([attribute="value"]);
Run Code Online (Sandbox Code Playgroud)
所以:
document.querySelector([data-foo="bar"]);
Run Code Online (Sandbox Code Playgroud)