Selecting multiple items with querySelectorAll

I have this piece of code:

var requiredFields = el.querySelectorAll("input[required]:not(:disabled):not([readonly]):not([type=hidden])"); 

If I want to add textarea and select to the request, I get the following:

 var requiredFields = el.querySelectorAll("input[required]:not(:disabled):not([readonly]):not([type=hidden])"+ ",select[required]:not(:disabled):not([readonly]):not([type=hidden])"+ ",textarea[required]:not(:disabled):not([readonly]):not([type=hidden])"); 

My feeling is that it could be better .. but how?

Bonus: please give me a good resource for the querySelectorAll function.

+8
javascript css-selectors selectors-api
source share
2 answers

As the Shadow Wizard said, at least you can remove the unnecessary :not([type=hidden]) in different places where it doesn't matter ( select and textarea ).

I do not see a problem with the result:

 var requiredFields = el.querySelectorAll( "input[required]:not(:disabled):not([readonly]):not([type=hidden])" + ",select[required]:not(:disabled):not([readonly])"+ ",textarea[required]:not(:disabled):not([readonly])"); 

... not least because it passes it all to the selector engine to take advantage of any optimization that it can do.

Alternatively, you can give all the relevant inputs a common class, and then use:

 var requiredFields = el.querySelectorAll( ".the-class[required]:not(:disabled):not([readonly]):not([type=hidden])"); 

... but I'm not sure that he buys you a lot.

Please give me a good resource for the querySelectorAll function.

There is a specification . MDN is also usually a good place for this material.

+6
source share

querySelectorAll


 window.l = ['input','textarea','select']; function myQuerySelectorAll() { q = ''; t = '[required]:not(:disabled):not([readonly]):not([type=hidden])'; l.forEach(function(e) { q += e; q += t; q += ','; }); console.log(q) } 

 $> myQuerySelectorAll(); $> input[required]:not(:disabled):not([readonly]):not([type=hidden]),textarea[required]:not(:disabled):not([readonly]):not([type=hidden]),select[required]:not(:disabled):not([readonly]):not([type=hidden]), 
+3
source share

All Articles