Simple way to clear the value of any input inside a div?

前端 未结 8 974
谎友^
谎友^ 2020-12-13 07:36

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 v

8条回答
  •  离开以前
    2020-12-13 08:10

    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.

提交回复
热议问题