Is there any vanilla JavaScript library for duplicate/clone form elements?

Hi, Can you help me?

I cannot find any library in vanilla JS for duplicating/cloning form elements. I can find a few snippets here and there, but not a proper library. Do you know any?

The reason I’m asking for a library, is because I have a page with multiple elements that needed to be cloned, so I believe that with a library, I can have a “cleaner” code.


Are you sure you need a library?

There are some caveats, like duplicating ids and missing event listeners.

Edit: Anyway, I don’t know of any libs off the top of my head I can recommend so it would just be some Google search result. jQuery has a .clone() method that also has withDataAndEvents/deepWithDataAndEvents options.

Actually, I have a few functions that do that job. But they are specific for just one set of elements. But on my page I have several set of elements that may be cloned (add/remove dynamically) by the user. So, the problem with my functions is that I need to duplicate them for each set of elements that I want to clone. If I could find a library or wrap those functions into a more “generic” way, then, I can reuse it, without bloating my code. However, I have zero knowledge about JS.

I can’t suggest anything you can’t find yourself by searching for it.

Without knowing more about the implementation it’s hard to give you much advice. But functions are usually not that hard to make generic by using parameters/arguments and a little logic inside to have different code paths. You do have to be careful that the abstraction doesn’t become bloated and tries to accommodate too many different use cases. So it’s often better to split it into multiple smaller functions (or OOP style with class/object/methods).

As for code bloat, you can make them utility functions that you import as needed.

This is what I have .

What do I need to do to make this more like a library?

You can create a function to deal with the id renaming. You pass it the element and do all the common renaming + incrementing to all element types.

Then check what type of element it is and do the clearing/resetting of the attributes (value, checked, etc.) from the element types as needed. You can also create more than one function so you have one specifically for clearing/resetting attributes.

I know this might be a bit vague but I’m guessing you can learn a lot from refactoring the code. Just take it a little bit at a time, start with the common renaming + incrementing, that shouldn’t be too difficult to create a generic function for.

Edit: Look at the repeating code and think about how you can put that inside a function that gets pass in an element as an argument.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.