使用部分ID查找元素 [英] Find elements using part of ID
问题描述
我有, div
,其中id看起来像 this_div_id_NUMBER
,所有 div
的具有不同的 NUMBER
部分。我如何找到所有 div
只是使用 this_div_id
id的一部分?
document.querySelectorAll([id ^ ='this_div_id'])
等号表示开始于,您可以使用*代替,但容易出现误报。
您还要确保使用引号(或围绕着attrib选择器中的comapare值,以便在querySelectorAll上达到最大兼容性;在jQuery和常青的浏览器中它并不重要,但在旧版浏览器的香草中它确实很重要。
编辑:最新破解需求需要一个更具体的选择器: document.querySelectorAll([id ^ ='this_div_id']:not([id $ ='_ test_field']));
not()段可防止任何以_test_field结尾的匹配项。
概念验证/演示: http: //pagedemos.com/partialmatch/
I have, the div
's where id looks like this_div_id_NUMBER
, all div
's has the different NUMBER
part. How I find all div
's just using this_div_id
part of id ?
you can use querySelectorAll to hit partial attribs, including ID:
document.querySelectorAll("[id^='this_div_id']")
the ^ next to the equal sign indicates "starts with", you can use * instead, but it's prone to false-positives.
you also want to make sure to use quotes (or apos) around the comapare value in attrib selectors for maximum compatibility on querySelectorAll; in jQuery and evergreen browsers it doesn't matter, but in vanilla for old browsers it does matter.
EDIT: late breaking requirement needs a more specific selector:
document.querySelectorAll("[id^='this_div_id']:not([id$='_test_field'])");
the not() segment prevents anything ending with "_test_field" from matching.
proof of concept / demo: http://pagedemos.com/partialmatch/
这篇关于使用部分ID查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!