Javascript 我可以在 queryselector() 中为 CONTAINS 使用属性选择器吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31773599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:10:41  来源:igfitidea点击:

Can I use an attribute selector for CONTAINS in queryselector()?

javascriptcss-selectors

提问by Doug Fir

I would like to select an element based on a substring of href attribute.

我想根据 href 属性的子字符串选择一个元素。

I posted a question recently where I received an answer based on "starts with":

我最近发布了一个问题,我收到了一个基于“开始于”的答案:

document.querySelector('#utility-menu a[href^="/email_check?lang="').textContent.trim();

But actually, the only constant from page to page will be "lang="within the href attribute. So /email_check?is page specific so I cannot use this variable on al pages.

但实际上,从页面到页面的唯一常量将"lang="在 href 属性内。所以/email_check?是页面特定的,所以我不能在所有页面上使用这个变量。

Is it possible to modify my selector to return the textContent of any <a>element with the substring "lang="within it?

是否可以修改我的选择器以返回<a>其中包含子字符串的任何元素的 textContent "lang="

回答by user4642212

All selectors are documented in the W3C Selectors Overview.

所有选择器都记录在W3C 选择器概述 中

The one you need is

你需要的是

#utility-menu a[href*="lang="]
E[foo*="bar"]

An Eelement whose fooattribute value contains the substring bar.

E[foo*="bar"]

Efoo属性值包含子字符串的元素bar

回答by Grant Miller

Consider the following HTML element:

考虑以下 HTML 元素:

<div id="utility-menu">
  <a href="/email_check?lang=en-US">Hello, world!</a>
</div>

You can obtain the first anchor elementthat has a hrefattribute containing 'lang='and exists as a descendant of an element with an idequivalent to 'utility-menu'using one of the following options:

您可以获得第一个锚元素,该元素href属性包含'lang='并作为元素的后代存在,id等效于'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='))