首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在不使用库的情况下querySelectorAll不可用时按属性获取元素?

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

Stack Overflow用户
提问于 2012-02-29 17:21:28
回答 7查看 269.9K关注 0票数 127
<p data-foo="bar">

您如何才能做到与

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

not available在哪里?querySelectorAll在哪里?

我需要一个本机解决方案,至少在IE7中工作。我不关心IE6。

EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2012-02-29 17:32:37

您可以编写一个运行数据(‘*’)的函数,并且只返回那些具有“getElementsByTagName-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');
票数 140
EN

Stack Overflow用户

发布于 2014-12-09 16:52:17

使用

//find first element with "someAttr" attribute
document.querySelector('[someAttr]')

//find all elements with "someAttr" attribute
document.querySelectorAll('[someAttr]') 

按属性查找元素。现在所有相关的浏览器(甚至是IE8)都支持它:http://caniuse.com/#search=queryselector

票数 65
EN

Stack Overflow用户

发布于 2017-05-17 20:41:52

试试这个,很管用。

document.querySelector('attribute="value"')

示例:

document.querySelector('[role="button"]')
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9496427

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档