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.
You can use an attribute contains selector ( *=
) with querySelector
(to find the first) or querySelectorAll
(to get a list of matches).
For instance:
const var1 = form.querySelector("[name*=foo]");
finds the first element in form
whose name
attribute contains the substring 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. The second will look for a foo
element first, and only look for a bar
element if no foo
is found.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.