当 querySelectorAll 在不使用库的情况下不可用时,按属性获取元素?

2024-05-08

<p data-foo="bar">

你怎样才能做到相当于

document.querySelectorAll('[data-foo]')

where 查询选择器全部 https://developer.mozilla.org/en/DOM/Document.querySelectorAll is 无法使用 http://caniuse.com/queryselector?

我需要一个至少可以在 IE7 中运行的本机解决方案。我不关心IE6。


您可以编写一个运行 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;
}

Then,

getAllElementsWithAttribute('data-foo');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 querySelectorAll 在不使用库的情况下不可用时,按属性获取元素? 的相关文章

随机推荐