简体   繁体   中英

Queryselector remove redundant comma separated list of items

Is there a grouping feature in the querySelector? Currently I have to list out all of the input types I want to match which results in redundant strings like this:

form.querySelectorAll('input[type=text], input[type=password], input[type=email], input[type=number]')

Is there a way to remove the redundancy to maybe look something like this:

form.querySelectorAll('input[type={text,password,email,number}]')

There's no built-in method that can do that, but it's easy to build your own function that can build a query string like that, allowing you to write more DRY code:

 const makeQuery = types => types.map(type => `input[type="${type}"]`).join(', '); console.log(makeQuery(['text', 'password', 'email', 'number'])) 

As far as CSS selectors go, there's only :matches . It doesn't make much of an improvement and doesn't work unprefixed in any browser except for Safari.

form.querySelectorAll(
    'input:matches([type=text], [type=password], [type=email], [type=number])')

You can build the string with JavaScript, though:

form.querySelectorAll(
    'text,password,email,number'.replace(/\w+/g, 'input[type=$&]'))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM