I would like to do something like:
var htmlcode = '<div>testing</div>';
document.getElementById('initDiv').html = htmlcode;
kinda like using innerHTML but replacing the element itself.
Can someone help me please? thanks
3 Answers 3
No, there's no native cross-browser solution to your problem. The best you could do would be to piece together something that will work in a more cross-browser manner.
Here's one solution:
function outerHTML( el, html ) {
if ( 'outerHTML' in el ) { // for most browsers
el.outerHTML = html;
} else { // for Firefox
var temp = document.createElement('div');
temp.innerHTML = html;
while (temp.firstChild) {
el.parentNode.insertBefore( temp.firstChild, el );
}
el.parentNode.removeChild(el);
}
};
Use it like this:
var initDiv = document.getElementById('initDiv');
outerHTML( initDiv, '<div>testing</div>' );
Example: http://jsfiddle.net/6VUNU/1/
Comments
There is a document.getElementById(...).outerHTML value that you can use, but as far as I remember it's not usable in all browsers.
Comments
You can always find initDiv's parent, createElement('div'), populate it with htmlcode, and then removeElement on the initDiv.
htmlcodevariable? Or would you be willing to usedocument.createElement()?