Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting multiple elements 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 the textarea and select to the query I'm ending up with this:

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 says this could be better.. but how?

Bonus: Please give me a good resource for querySelectorAll function.

like image 505
A1rPun Avatar asked Dec 19 '13 09:12

A1rPun


Video Answer


1 Answers

As Shadow Wizard said, at a minimum you can remove the unnecessary :not([type=hidden]) in the various places it has no meaning (select and textarea).

I don't 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 hands the whole thing off to the selector engine to take advantage of any optimization it can do.

Alternately you could give all of 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 it buys you much.

Please give me a good resource for querySelectorAll function.

There's the specification. MDN is also usually a good place for this stuff.

like image 126
T.J. Crowder Avatar answered Nov 15 '22 21:11

T.J. Crowder