0

How do you select dynamically added elements

I am creating checkboxes upon an onclick event. Once those checkboxes are created i want to perform an action on them but it only performs on the first checkbox since the Id only recognizes that. I want to select all of them. A for loop does not work either

19th Dec 2020, 9:38 AM
Dee
2 Answers
+ 3
Dee You can use querySelectorAll. var checkboxes = document.querySelectorAll('input[name="vechicle"]:checked'); for (var checkbox of checkboxes) { document.body.append(checkbox.value + ' '); } https://www.techiedelight.com/retrieve-checked-checkboxes-values-javascript/ https://www.includehelp.com/code-snippets/javascript-print-value-of-all-checked-selected-checkboxes.aspx
19th Dec 2020, 9:45 AM
A͢J
A͢J - avatar
0
You must be sure the elements are really rendered to the dom before grabbing them. how can you do that? Well, you have many options: 1- attaching "onchange" even to the parent element you dynamically add into it 2- make the actions you want to do on the dynamically added elements in a separate function, that's only triggered after elements added by some time (consider setTimeout() for example) 3- i have looked for it and it appears that there is something called "mutation observer" API that lets you detect any dom change and acts upon it
19th Dec 2020, 11:01 AM
Ali Kh
Ali Kh - avatar