[英]How to check if element name contains the given string
In the code below I`m checking if these 2 elements exist.在下面的代码中,我正在检查这两个元素是否存在。
const var1 = form.elements[elemName1] ||
form.elements[elemName2]
if(var1){
doSmth
}
But what I need is to check if element's name contains a certain string.但我需要的是检查元素的名称是否包含某个字符串。 Like:
喜欢:
const var1 = form.elements[NameContains(givenString)] ||
form.elements[NameContains(givenString)]
I tried to find the needed syntax in google bud did not succeeded.我试图在 google bud 中找到所需的语法没有成功。
You can use an attribute contains selector ( *=
) with querySelector
(to find the first) or querySelectorAll
(to get a list of matches).您可以将属性包含选择器(
*=
) 与querySelector
(查找第一个)或querySelectorAll
(获取匹配列表)一起使用。
For instance:例如:
const var1 = form.querySelector("[name*=foo]");
finds the first element in form
whose name
attribute contains the substring foo
.在
form
查找name
属性包含子字符串foo
的第一个元素。 Similarly there's ^=
for "starts with" and $=
for "ends with."类似地,
^=
表示“开始于”,而$=
表示“结束于”。
If you're checking for two different substrings, either use a selector group:如果您要检查两个不同的子字符串,请使用选择器组:
const var1 = form.querySelector("[name*=foo], [name*=bar]");
or two calls:或两个电话:
const var1 = form.querySelector("[name*=foo]") || form.querySelector("[name*=bar]");
The difference between those is that the selector group will find the first matching element in document order, whether it's a foo
or bar
element.它们之间的区别在于选择器组将查找文档顺序中的第一个匹配元素,无论是
foo
元素还是bar
元素。 The second will look for a foo
element first, and only look for a bar
element if no foo
is found.第二个将首先查找
foo
元素,如果没有找到foo
则只查找bar
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.