I wanted to remove a element from a copy of the main DOM however i cannot get it to work.
Basically i am trying to remove the h2 element from the duplicate DOM and return the modified code in an alert however with whatever i have tried so far i just get the original DOM still.
<html>
<head>
</head>
<body>
<h2>Test</h2>
<script type="text/javascript" id="CustomScript">
var Page = document.documentElement;
var TempPage = document.documentElement;
TempPage.removeChild("h2"); // Remove Not working
TempPage.getElementById("h2").innerHTML = ""; // Remove Not working
</script>
<input type="button" value="Get Pages Code" onclick="alert(TempPage.innerHTML)">
</body>
</html>
If possible i would rather not use jQuery or YUI etc and just want to use regular Javascript.
There are two parts to your question and you are doing them both incorrectly.
TempPageis the same object asPage. Assignment to a different variable does not make a copy–it just lets you access the same object via another name. You need to explicitly create a copy.h2element are both incorrect.removeChild()won’t work because:documentElementis the<html>element, but the<h2>element is a child of<body>, not<html>.getElementById()won’t work because your<h2>element does not have an id attribute.How you would do this is:
If
querySelectoris not available, this will be a much more tedious task but still possible using normal DOM manipulation. You really need to learn about DOM manipulationHowever from your complete code I can’t fathom why you would need to clone the page. Just do this: