Home > Software design >  querySelectorAll with multiple attributes and a dynamic value
querySelectorAll with multiple attributes and a dynamic value

Time:12-21

I need to find all the selected checkbox items on a page and an attribute matches a particular value. So, for example, in the snippet below the 'pageid' attribute could be a dynamic value

<input type="checkbox" pageid="5" />

I thought a template string might help me, and I've tried the following..

 let checkboxes = document.querySelectorAll(
              `[input[type="checkbox"]:checked][pageid=${myPageIDVariable}]`
            );

Sadly this gives me an error like the one below, but I'm not sure why it's considered invalid.

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '[input[type="checkbox"]:checked][pageid=3]' is not a valid selector.

I even tried hardcoding the pageid value, to no avail.

Any help/guidance would be truly appreciated...

CodePudding user response:

This is probably the query you were looking for

let myPageIDVariable = 5;

let checkboxes = document.querySelectorAll(
  `input[type="checkbox"][pageid="${myPageIDVariable}"]:checked`
);

console.log(Array.from(checkboxes));
<input type="checkbox" pageid="5" />

  • Related