Efficiency Question
Efficiency Question
I'm just a few weeks into js/jQuery and have run into a nagging question about DOM manipulation efficiency that I've been unable to answer for myself without relying on assumptions. Here's a simple manipulation example:
HTML from:
- <div id="top">
</div>
<div id="bottom">
<a href="#" id="one"></a>
<a href="#" id="two"></a>
<a href="#" id="three"></a>
</div>
HTML to:
- <div id="top">
<div id="top-inner">
<a href="#" id="one"><div></div></a>
<a href="#" id="two"><div></div></a>
<a href="#" id="three"><div></div></a>
</div>
</div>
<div id="bottom">
</div>
Here are two jQuery snippets that will accomplish the task:
jQuery 1:
- var a = $('div#bottom').children();
a.append('<div></div>');
$('<div id="top-inner"></div>').append(a).appendTo('div#top');
jQuery 2:
- var a = $('div#bottom').children();
var d = $('<div id="top-inner"></div>');
a.appendTo(d).append('<div></div>');
d.appendTo('div#top');
I'm leaning to the second jQuery snippet being more efficient. I'm basing this on the assumption that the moved elements are being removed from the DOM before any further manipulation, and then placed back in the DOM wrapped in the single div. Is this assumption correct?
I'm aware that this very simple example may just be dealing with a difference of nanoseconds, but any info offered will be helpful to approaching more complex tasks.
Thanks