View Full Version : Element Extraction
Antoniohawk
06-29-2005, 12:16 AM
Is it possible to somehow set a variable equal to an element within a page, wipe everything in the body tag and then put the element and its children back into the page?
<body>
<div id="myDiv">
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</body>to
<body>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</body>
Antoniohawk
06-29-2005, 12:28 AM
Well, I guess that I should have waited a little longer before asking how to do it because I figured it out.
var d = document.getElementById(name of element to extract);
document.body.innerHTML = '';
document.body.appendChild(d);I bet that there's a much browser-friendly way to do it though. Any ideas?
in fact your problem is to remove a Node. the method removeNode() exists, but unfortunatelly is an IE only method (removeNode() and innerHTML are amongs the few good IE's extensions... :D )
I had a similar problem and I have used a trick. My problem was to remove all the links in a text, at that time my solution was to replace the a tags with neutralspan tags:
In your case you should do otherwise. Your code is not quite DOM standard. On the other hand what if your div has more than one childNode? So that try this, I hope, general solution
<script type="text/javascript">
function removeN(){
var el = document.getElementById('myDiv');
var kids = el.childNodes;
for(var i=0;i<kids.length;i++){
var cloned = kids[i].cloneNode(true);
el.parentNode.insertBefore(cloned,el)
}
el.parentNode.removeChild(el)
}
</script>
Antoniohawk
06-30-2005, 01:48 AM
Very nice. I'm surprised that I actually understand what's going on there. Thanks Kor.
SpirtOfGrandeur
07-01-2005, 05:28 PM
Here is the DOM Compliant Way... Like KOR said you dont know if 'mydiv' has more then one child.
var d = document.getElementById('ID');
if ( d.parentNode ) d.parentNode.removeChild(d);
while ( d.firstChild ) {
document.body.appendChild(d.removeChild(d.firstChild));
}
Note: This was not verified... just off the top of my head!
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.