簡體   English   中英

如何在 Javascript 中使用部分字符串匹配的 select 類

[英]How to select classes with partial string match in Javascript

<div class="xyz">
<cite class="abc hello pqr">Text inside</cite>
<cite class="hello">Text inside</cite>
<cite class="abc hello">Text inside</cite>
</div>

這是 class 的示例,其中 substring “你好”。 使用 JavaScript,我想 select 所有出現“hello”的類,並進一步修改所選類的innerHTML 請注意,substring 可以出現在 class 名稱中的任何位置。

我遇到的所有問題都只能選擇 select 所有id包含 substring 的元素。 例如。

document.querySelectorAll('[id^="hello-"]');

當我修改以使其適用於課程時

document.querySelectorAll('[class^="hello-"]');

它根本不起作用。

我需要用於查找“hello”為 substring 的所有類的代碼,並進一步修改所選類的innerHTML 請僅使用 JavaScript 建議代碼

我認為您正在尋找屬性選擇器* ,您正在使用^

所以,按照你的例子

// from
document.querySelectorAll('[class^="hello-"]');

// to
document.querySelectorAll('[class*="hello"]');

您對屬性選擇器的工作方式有一點誤解

您使用[class^="hello-"]所做的是匹配所有以hello-的類

使用另一個示例[class*="hello"] ,您將匹配所有包含hello的類

您可以查看W3C 選擇器概述以獲取更多信息。 這類似於您使用 RegEx 的方式。

使用. 當調用querySelectorAll以指示要查找的 class 名稱時。

 for (const cite of document.querySelectorAll('.hello')) { cite.textContent = 'new text'; }
 <div class="xyz"> <cite class="abc hello pqr">Text inside</cite> <cite class="hello">Text inside</cite> <cite class="abc hello">Text inside</cite> <cite class="abc">don't match me</cite> </div>

如果您正在尋找特定的 class,則不要將 select 視為 substring。 您使用特殊的.class選擇器。

document.querySelectorAll(".hello")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM