【问题标题】:document querySelectorAll to find part of elements's attribute name? [duplicate]文档 querySelectorAll 以查找元素的部分属性名称? [复制]
【发布时间】:2019-11-10 22:12:28
【问题描述】:

我尝试选择页面上具有ARIA 属性的所有元素,以检查页面是否正确使用它们。 众所周知,属性以 aria-[NAME] 开头。

由于我不能将regex 与元素选择器一起使用,并且css selectors 没有让我选择通配符选择属性 名称(或者是吗?),我想知道我该怎么做?

简单的测试页面:

<div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" ></div>
<div class="text">
  <label id="tp1-label" for="first">First Name:</label>
  <input type="text" id="first" name="first" size="20" aria-labelledby="tp1-label" aria-describedby="tp1" aria-required="false" />
  <div id="tp1" class="tooltip" role="tooltip" aria-hidden="true">Your first name is optional</div>
</div>

<script>
let elAria1 = document.querySelectorAll('[aria-*]'); // this doesn't work
let elAria2 = document.querySelectorAll('[aria-'*]); // this doesn't work either
let elAria3 = document.querySelectorAll([aria-*]); // this doesn't work too
</script>

【问题讨论】:

  • @DavidThomas 我想知道我怎么没看到!谢谢你!
  • 不客气 :)

标签: javascript css-selectors


【解决方案1】:

是的,除非您已经拥有需要查找的属性名称列表,否则无法使用查询字符串来筛选您想要的属性名称。您必须通过检查元素的任何属性是否以 aria 开头,以更编程的方式进行操作:

const ariaElements = [...document.querySelectorAll('*')]
  .filter(elm => [...elm.attributes].some(
    ({ name }) => name.startsWith('aria-')
  ));
console.log(ariaElements);
<div id="percent-loaded" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" ></div>
<div class="text">
  <label id="tp1-label" for="first">First Name:</label>
  <input type="text" id="first" name="first" size="20" aria-labelledby="tp1-label" aria-describedby="tp1" aria-required="false" />
  <div id="tp1" class="tooltip" role="tooltip" aria-hidden="true">Your first name is optional</div>
</div>

【讨论】:

  • 感谢您提供的这个极简紧凑的好例子!
  • 我已将问题作为重复项关闭,但我确实喜欢您的回答,因为它简洁且使用现代语法。您会考虑将您的答案添加到链接的欺骗中吗?我考虑添加到我自己现有的答案中,但这感觉有点像抄袭。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
  • 2019-09-30
相关资源
最近更新 更多