Alex Rivera | Logout

Why should y.innerHTML = x.innerHTML; be avoided?

Asked 2011-09-12T19:29:47.267
47

Let's say that we have a DIV x on the page and we want to duplicate ("copy-paste") the contents of that DIV into another DIV y. We could do this like so:

y.innerHTML = x.innerHTML;

or with jQuery:

$(y).html( $(x).html() );

However, it appears that this method is not a good idea, and that it should be avoided.

(1) Why should this method be avoided?

(2) How should this be done instead?


Update:
For the sake of this question let's assume that there are no elements with ID's inside the DIV x.
(Sorry I forgot to cover this case in my original question.)

Conclusion:
I have posted my own answer to this question below (as I originally intended). Now, I also planed to accept my own answer :P, but lonesomeday's answer is so amazing that I have to accept it instead.

Edit
Report

2 Answers

10
  1. You can duplicate IDs which need to be unique.
  2. jQuery's clone method call like, $(element).clone(true); will clone data and event listeners, but ID's will still also be cloned. So to avoid duplicate IDs, don't use IDs for items that need to be cloned.
answered 2011-09-12T19:31:10.277
4

I wouldn't do it simply because you're asking the browser to re-parse HTML markup that has already been parsed.

I'd be more inclined to use the native cloneNode(true) to duplicate the existing DOM elements.

var node, i=0;

while( node = x.childNodes[ i++ ] ) {
    y.appendChild( node.cloneNode( true ) );
}
answered 2011-09-12T19:41:06.763

Your Answer