Set checked state of a nodelist of checkboxes

Viewed 1036

I have a nodelist of checkboxes. How can I set them all to be checked? The following forEach does not work as the property checked does not exist on type element

let checkboxes = document.querySelectorAll('[id^="chkAddProposalProduct_"]');

checkboxes.forEach(c => { c.checked = true});

HTML

<input type="checkbox" id="chkAddProposalProduct_{{product.productId}}">
1 Answers

TypeScript has no way to know that checkboxes contains only <input type="checkbox"> elements. You could have any element with an ID starting with chkAddProposalProduct_. So you need to tell the TypeScript compiler that checkboxes is an NodeList of HTMLInputElement objects, like so:

let checkboxes = document.querySelectorAll('[id^="chkAddProposalProduct_"]') as NodeListOf<HTMLInputElement>;

checkboxes.forEach(c => { c.checked = true; });
Related