Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  158] [ 4]  / answers: 1 / hits: 33230  / 15 Years ago, wed, september 30, 2009, 12:00:00

Is there a simple way to iterate over the child elements in an element, say a div, and if they are any sort of input (radio, select, text, hidden...) clear their value?



Edit to add link to example solution code. Many thanks to Guffa and the other respondents! I learned from this!


More From » forms

 Answers
209

I suppose that you want to clear all children, not only the direct children, so it would have to be recursive. As different input elements is cleared differently, you have to check their type so that you know what to do with them. I suppose that you want to clear textareas also, but leave buttons unchanged:



function clearChildren(element) {
for (var i = 0; i < element.childNodes.length; i++) {
var e = element.childNodes[i];
if (e.tagName) switch (e.tagName.toLowerCase()) {
case 'input':
switch (e.type) {
case radio:
case checkbox: e.checked = false; break;
case button:
case submit:
case image: break;
default: e.value = ''; break;
}
break;
case 'select': e.selectedIndex = 0; break;
case 'textarea': e.innerHTML = ''; break;
default: clearChildren(e);
}
}
}


Call it with a reference to the element:



clearChildren(document.getElementById('IdOfTheDiv'));


Edit:

Forgot the select...



Edit 2:

Some corrections: childNodes.length, handling elements without tagName and uppercase tagName values.


[#98587] Saturday, September 26, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;