Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Is there a better way of duplicating elements? Reply To: Is there a better way of duplicating elements?

#190550
Senff
Participant

Using classes would certainly work but I’m trying to make it sort of a plugin that can be used on existing html.

This is exactly the reason I used the clone() method. My Sticky Menu plugin (see below for example) creates a clone of an existing element, and that new clone will have the ID and all the classes that the original element has.

Yes, indeed you can end up with two elements on one page with the same ID. Which is not valid and violates the rules…but it works. After doing much research, it was really the only way I could find to ensure it the clone will have the same styles as the original.

Taking the styles from the original element and then apply them to the new one…in theory that would be great, but it just couldn’t be done without much, much more work. The more I tried, to more problems I ran into.

And so, in the end I just accepted “defeat” and went with the duplicate IDs. In practice, it didn’t break anything for my plugin (but that may have to do with the fact that it was either the original OR the clone visible on the page, and never both at the same time).

http://codepen.io/senff/pen/ayGvD