Categories
JavaScript Answers

How to clone a file input element in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to clone a file input element in JavaScript?”

Leave a Reply

Your email address will not be published. Required fields are marked *