使用 querySelectorAll() 获取以特定字符串开头但不以特定字符串结尾的元素
Getting element with querySelectorAll() that starts with a certain string but does NOT end with a certain string
我正在处理的页面有许多相似元素,所有这些元素的 id 都以字符串“text_d”开头,但一半在末尾有一个额外的“_description”。我想为所有这些不以描述结尾的事件添加一个事件监听器。
我知道 startsWith 和 endsWith 符号 (^=,$=),而且我听说过 not(),所以我尝试了这个:
elements = document.querySelectorAll('*[id^="text_d"]','*:not(*[id$="description"])');
但无济于事。有没有办法做到这一点?或者我是否必须诉诸全部选择它们,然后在事件侦听器函数中用
之类的东西整理出不需要的那些
if(!element.id.endWith("_description")){...}
您需要将 :not 选择器链接到第一个参数:
elements = document.querySelectorAll('[id^=text_d]:not([id*=description])');
elements.forEach(e=>e.style.color="red")
<div id="text_d">1</div>
<div id="text_d">2</div>
<div id="text_d_description">not</div>
你的第二种方法很好,只是不是 endwith
,而是 endsWith
:
elements = document.querySelectorAll('[id^=text_d]');
elements.forEach(e=> !e.id.endsWith("_description") ? e.style.color="red" : null)
<div id="text_d">1</div>
<div id="text_d">2</div>
<div id="text_d_description">not</div>
当您收到控制台错误 * is not a function 时,请务必检查 * 某物。
我正在处理的页面有许多相似元素,所有这些元素的 id 都以字符串“text_d”开头,但一半在末尾有一个额外的“_description”。我想为所有这些不以描述结尾的事件添加一个事件监听器。
我知道 startsWith 和 endsWith 符号 (^=,$=),而且我听说过 not(),所以我尝试了这个:
elements = document.querySelectorAll('*[id^="text_d"]','*:not(*[id$="description"])');
但无济于事。有没有办法做到这一点?或者我是否必须诉诸全部选择它们,然后在事件侦听器函数中用
之类的东西整理出不需要的那些if(!element.id.endWith("_description")){...}
您需要将 :not 选择器链接到第一个参数:
elements = document.querySelectorAll('[id^=text_d]:not([id*=description])');
elements.forEach(e=>e.style.color="red")
<div id="text_d">1</div>
<div id="text_d">2</div>
<div id="text_d_description">not</div>
你的第二种方法很好,只是不是 endwith
,而是 endsWith
:
elements = document.querySelectorAll('[id^=text_d]');
elements.forEach(e=> !e.id.endsWith("_description") ? e.style.color="red" : null)
<div id="text_d">1</div>
<div id="text_d">2</div>
<div id="text_d_description">not</div>