我需要在它們的類名末尾找到一組元素,它與通過 Name 或 ID 的一部分獲取元素非常相似,但是使用document.querySelectorAll([class~=<constant string>])不起作用但[class=<full class name包括隨機字符(見下文)確實有效。
有問題的元素有一個類名,如。(三個字符的隨機字串)-(一些常量字串)是否可以通過(一些常量字串)找到它們?
uj5u.com熱心網友回復:
- 正確的語法是
$=查找以特定字串結尾的類。 - 如果您想在該選擇器中使用變數,請使用模板字串插入它。
const constant = '123';
const divs = document.querySelectorAll(`[class$="${constant}"]`);
divs.forEach(div => console.log(div.textContent));
<div class="abc-123">Will be selected 1</div>
<div class="def-234">Will not be selected 1</div>
<div class="ghi-123">Will be selected 2</div>
<div class="jkl-234">Will not be selected 2</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489567.html
標籤:javascript html css dom
