是的,但它不存在于所有的浏览器。旧版本的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这样的库可以为你处理这个问题:让它们完成繁重的工作可能是一个好主意。
你能否解释一下为什么你需要做的是专门这样?这是非常低效的,并有更好的方法来处理它。 – 2011-10-04 16:44:38