skip to Main Content

I have a function:-

function resetInputFile(elem) {
    elem.wrap('<form>').closest('form').get(0).reset();
    elem.unwrap();
}

I call the function like this:-

resetInputFile(document.queryElement('#image'));

How can I convert the LOCs

elem.wrap('<form>').closest('form').get(0).reset();
elem.unwrap();

into pure javascript?

I want to implement the logic in ReactJS, but I don’t want to use jquery with ReactJS. So I need to do it with pure javascript.

2

Answers


  1. You can try something like:

    function resetInputFile(elem) {
      const form = document.createElement('form');
      const parent = elem.parentNode;
    
      parent.insertBefore(form, elem);
      form.appendChild(elem);
      form.reset();
      parent.insertBefore(elem, form);
      parent.removeChild(form);
    }
    
    function resetFileInput() {
      resetInputFile(document.querySelector('#image'));
    }
    <input type="file" id="image">
    <button onclick="resetFileInput()">Reset File Input</button>
    Login or Signup to reply.
  2. function resetInputFile() {
      const elem = document.getElementById('image'); //--Get the input element
    
      const form = document.createElement('form'); //--> Create a <form> element
      const parent = elem.parentNode;//-- Get the parent node of elem
    
      //-->Replace elem with the newly created form, moving elem inside the form
      parent.replaceChild(form, elem);
      form.appendChild(elem);
    
      //--Reset the form
      if (form && form.parentNode) {
        form.reset();
        // Restore elem to its original position outside the form
        form.parentNode.replaceChild(elem, form);
      }
    
      // Unwrap the element
      if (elem.parentNode) {
        const grandParent = elem.parentNode.parentNode; //--> Get the grandparent node
        grandParent.replaceChild(elem, elem.parentNode); //--->Replace form with elem
      }
    }
    <input type="file" id="image" />
     <button onclick="resetInputFile()">Reset Input File</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search