简体   繁体   English

如何检查元素名称是否包含给定的字符串

[英]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.

相关问题 如何使用javascript检查HTMLCollection是否包含具有给定类名的元素? - How to check if an HTMLCollection contains an element with a given class name using javascript? 如何检查数组是否包含给定元素 - How to check in array if it contains given element 如何检查 URL 是否包含给定的字符串? - How to check if the URL contains a given string? 如何检查给定单词是否包含在字符串中? - How to check whether a given word contains in String? 如何使用jQuery检查字符串是否包含给定的字符串 - How to check if a string contains a given string using jQuery 如何检查android浏览器中的URL是否包含给定的字符串? - How to check if the URL in android browser contains a given string? 如何检查我网站上另一个框架的URL是否包含给定的字符串? - How to check if the URL of another frame on my site contains a given string? jasmine:检查数组是否包含具有给定属性的元素 - jasmine: check that an array contains an element with given properties 如何检查字符串是否包含数组中的某个元素,但不包含其他元素 - How to check if a string contains a certain element from an array, but not the other elements 将所有内容转换为小写后如何检查元素是否包含字符串 - How to check if element contains string after converting everything to lowercase
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM