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
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
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