Question

I have a search box somewhere on top of my layout

<input type="text" id="rec_search_input" ...>

I want to clone this element to a second spot, it must look the same and behave the same.

Now I know an ID must be unique, but,.. imagine like a unix symlink, having the same file accessable from different directories.

Is it possible to clone a DOM element and reuse its attached styles + event handlers, ... ?

Was it helpful?

Solution

A proper solution would be to give the .cloneNode() a new ID, and only apply CSS to the element's class rather than its ID. So:

var clone = document.getElementById("rec_search_input").cloneNode();
clone.id = "some other id";

...and then append that elsewhere in the DOM (e.g., via appendChild, insertBefore, etc.). (Side note: Since your element is an input, it can't have children, but if you use this for other things, you can use cloneNode(true) to clone its descendant elements; then spin through them to be sure their id values are unique.)

To some extent, you can "cheat". ID uniqueness isn't enforced by the browser or anything, and CSS will apply to elements with the same ID even if there are more than one. Demo

However, as you are probably aware, JavaScript functions like getElementById will not work predictably if you have duplicate IDs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top