If you move the elements around the DOM as objects rather than a primitive string representation, their attached events and other meta will be maintained.
You'll need to utilize the DOM's appendChild
and insertBefore
methods. Fiddle: http://jsfiddle.net/QMLpL/2/
Here is your updated snippet:
prepend: function(newNode) {
this.node.insertBefore(newNode,this.node.firstChild);
},
append: function(newNode) {
this.node.appendChild(newNode);
}
The updated snippet expects a DOM node rather than a string.
If you are expecting a string, consider utilizing the string as a CDATA node:
node = document.createTextNode(str);
Enhanced fiddle: http://jsfiddle.net/QMLpL/3/
Usage:
prepend: function(str) {
newNode = document.createTextNode(str);
this.node.insertBefore(newNode,this.node.firstChild);
},
append: function(str) {
newNode = document.createTextNode(str);
this.node.appendChild(newNode);
}
The contents of the linked fiddle are as follows.
HTML:
<div id="one">
<p><a id="clicky" href="#">Hello World</a></p>
</div>
<div id="two">
<p>Lorem Ipsum</p>
</div>
JavaScript:
var clicky = document.getElementById('clicky');
clicky.onclick = function() {
console.log('clicked!');
return false;
};
function append(target,node) {
if ( typeof node === 'string' ) {
node = document.createTextNode(node); // cast string as CDATA
}
target.appendChild(node);
}
function prepend(target,node) {
if ( typeof node === 'string' ) {
node = document.createTextNode(node);
}
target.insertBefore(node,target.firstChild);
}
var twoDiv = document.getElementById('two');
append(twoDiv,clicky);
var newElement = document.createElement('p');
newElement.onclick = function() {
console.log('clicked the p');
return false;
};
newElement.appendChild(document.createTextNode('Dolor sit amet.')); // add a CDATA node to the new P element
prepend(twoDiv,newElement);
append(twoDiv,'Waddup?');