MagicHat
MagicHat

Reputation: 429

Exclude specific element by id on querySelectorAll

I try get length of an array from:

document.querySelectorAll('select,input,textarea');
alert(Object.keys(arr).length);//19

Inside that array i have to exclude 4 elements, being 2 input type="hidden", and 2 with specif id's, so i try use :not selector:

document.querySelectorAll('select,input,textarea,input:not[type="hidden",input:not[id="input_up_img_perfil"],input:not[id="sub_img_perfil"],');
alert(Object.keys(arr).length);//19

What is the right sintax for that query?

Upvotes: 6

Views: 10328

Answers (3)

sjahan
sjahan

Reputation: 5960

Try this:

document.querySelectorAll('select,input:not([type="hidden"]):not(#input_up_img_perfil):not(#sub_img_perfil),textarea');

It should work pretty fine ;)

It is actually pretty simple: first, you need to add parenthesis to the :not operator. Then, you need to think about the proper CSS query to select what you need.

Example that will not work:

'input:not([type="hidden"]),input:not(#input_up_img_perfil),input:not(#sub_img_perfil)'

because you have actually three queries and the result will be merged at the end, since input:not(#input_up_img_perfil) has no constraint on the hidden fields, you'll get them in the result even though you set input:not([type="hidden"]).

That's why you need to do the following:

'input:not([type="hidden"]):not(#input_up_img_perfil):not(#sub_img_perfil)'

Here, you have only one query on the input tag, with three constraints!

Hope this is clear ;)

Upvotes: 13

sree
sree

Reputation: 389

For Example

<input class="test">
<input class="test asd">

Try something like this:

document.querySelectorAll('span.test:not(.asd)');

Instead of:

document.querySelectorAll('select,input,textarea,input:not[type="hidden",input:not[id="input_up_img_perfil"],input:not[id="sub_img_perfil"],');

Upvotes: 2

31piy
31piy

Reputation: 23859

You may convert the collection of nodes to an array, and then use Array#filter to filter out the non-required elements:

Array.from(document.querySelectorAll('select,input,textarea'))
  .filter(item => item.type !== 'hidden' || item.id !== 'input_up_img_perfil' || item.id !== 'sub_img_perfil');

Upvotes: 1

Related Questions