当 querySelectorAll 在不使用库的情况下不可用时,按属性获取元素? [英] Get elements by attribute when querySelectorAll is not available without using libraries?

查看:25
本文介绍了当 querySelectorAll 在不使用库的情况下不可用时,按属性获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<p data-foo="bar">

你怎么能做到等价于

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

其中 querySelectorAll不可用?

我需要一个至少适用于 IE7 的本机解决方案.我不在乎 IE6.

I need a native solution that works at least in IE7. I don’t care about IE6.

推荐答案

您可以编写一个运行 getElementsByTagName('*') 的函数,并仅返回具有data-foo"属性的那些元素:

You could write a function that runs getElementsByTagName('*'), and returns only those elements with a "data-foo" attribute:

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');

这篇关于当 querySelectorAll 在不使用库的情况下不可用时,按属性获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆