我想根据href属性的子字符串选择一个元素。
我最近发布了一个问题,我收到的答案基于"以"开头:
document.querySelector('#utility-menu a[href^="/email_check?lang="').textContent.trim();
但实际上,页面之间的唯一常量将是href属性中的"lang="
。所以/email_check?
是特定于页面的,所以我不能在al。页面上使用这个变量。
是否可以修改我的选择器以返回其中包含子字符串<a>
的任何"lang="
元素的textContent?
答案 0 :(得分:24)
所有选择器都记录在W3C Selectors Overview。
中你需要的是
#utility-menu a[href*="lang="]
E[foo*="bar"]
E
元素,其foo
属性值包含子字符串bar
。
答案 1 :(得分:1)
考虑以下HTML元素:
<div id="utility-menu">
<a href="/email_check?lang=en-US">Hello, world!</a>
</div>
您可以获得第一个anchor element,该href
属性包含'lang='
,其属性为id
,并且作为元素的后代存在,其元素{{3}}等同于'utility-menu'
使用以下选项之一:
// Using the [attr*=value] selector (best option)
document.querySelector('#utility-menu a[href*="lang="]')
// Using the find() method (alternative option)
[...document.querySelectorAll('#utility-menu a[href]')].find(e => e.href.includes('lang='))