How to clone a file input element in JavaScript?

Sometimes, we want to clone a file input element in JavaScript.

In this article, we’ll look at how to clone a file input element in JavaScript.

How to clone a file input element in JavaScript?

To clone a file input element in JavaScript, we can use the cloneNode method.

For instance, we write:

<input type='file'>

to add a file input.

Then we write:

const input = document.querySelector('input')
const inputClone = input.cloneNode(true)
document.body.appendChild(inputClone)

to select the file input with querySelector.

Then we call input.cloneNode with true to do a deep clone of the input and return it.

Finally, we call document.body.appendChild with inputClone to append it as a child of the body element.

Conclusion

To clone a file input element in JavaScript, we can use the cloneNode method.