[英]Can I use an attribute selector for CONTAINS in queryselector()?
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.但实际上,从页面到页面的唯一常量将是 href 属性中的
"lang="
。 So /email_check?
所以
/email_check?
is page specific so I cannot use this variable on al pages.是特定于页面的,所以我不能在所有页面上使用这个变量。
Is it possible to modify my selector to return the textContent of any <a>
element with the substring "lang="
within it?是否可以修改我的选择器以返回其中包含子字符串
"lang="
的任何<a>
元素的 textContent ?
All CSS selectors are documented on MDN and specified in the W3C CSSWG Selectors Level 4 overview 1 ( Archived link ).所有 CSS 选择器都记录在MDN 上,并在W3C CSSWG 选择器级别 4 概述1 ( 存档链接)中指定。
The one you need is你需要的是
#utility-menu a[href*="lang="]
Pattern 图案
Represents 代表
E[foo*="bar"]
An E
element whosefoo
attribute value contains the substringbar
.一个
E
元素,其foo
属性值包含子字符串bar
。
1 : The CSSWG's current work of the CSS Selectors Module is Selectors Level 4. Not all of its features are supported in all browsers. 1 :CSSWG 目前的 CSS Selectors Module 工作是 Selectors Level 4。并非所有浏览器都支持其所有功能。 The Level 4 draft includes everything from Level 1 to Level 4. Watch the “Level” table column.
级别 4 草案包括从级别 1 到级别 4 的所有内容。请查看“级别”表列。 Today's browsers support at least up to Level 3, but check the compatibility tables on MDN to be sure.
今天的浏览器至少支持级别 3,但请检查MDN上的兼容性表以确保。
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 element that has a href
attribute containing 'lang='
and exists as a descendant of an element with an id
equivalent to 'utility-menu'
using one of the following options:您可以使用以下选项之一获取具有包含
'lang='
的href
属性并作为具有等同于'utility-menu'
的id
的元素的后代存在的第一个锚元素:
// 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='))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.