問題描述
我想根據 href 屬性的子字符串選擇一個元素.
我最近發布了一個問題,我收到了一個基于開始于"的答案:
document.querySelector('#utility-menu a[href^="/email_check?lang="').textContent.trim();
但實際上,從一個頁面到另一個頁面的唯一常量是 href 屬性中的 "lang="
.所以 /email_check?
是特定于頁面的,所以我不能在所有頁面上使用這個變量.
是否可以修改我的選擇器以返回任何 <a>
元素的 textContent,其中包含子字符串 "lang="
?
所有 CSS 選擇器都記錄在 MDN 并在 W3C CSSWG 選擇器級別 4 概述中指定1 (存檔鏈接).
你需要的是
#utility-menu a[href*="lang="]
<塊引用>
模式 | 代表 |
---|---|
E[foo*=bar"] | 一個 E 元素,其 foo 屬性值包含子字符串 bar . |
1:CSSWG 目前的 CSS 選擇器模塊工作是選擇器級別 4.并非所有瀏覽器都支持其所有功能.4 級草案包括從 1 級到 4 級的所有內容.觀看級別"表列.今天的瀏覽器至少支持 Level 3,但請查看 兼容性表在 MDN 上確定.
I would like to select an element based on a substring of href attribute.
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.
Is it possible to modify my selector to return the textContent of any <a>
element with the substring "lang="
within it?
All CSS selectors are documented on MDN and specified in the W3C CSSWG Selectors Level 4 overview1 (Archived link).
The one you need is
#utility-menu a[href*="lang="]
Pattern Represents E[foo*="bar"]
An E
element whosefoo
attribute value contains the substringbar
.
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. The Level 4 draft includes everything from Level 1 to Level 4. Watch the "Level" table column. Today’s browsers support at least up to Level 3, but check the compatibility tables on MDN to be sure.
這篇關于我可以在 queryselector() 中為 CONTAINS 使用屬性選擇器嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!