简体   繁体   中英

Removing elements from a DOM copy

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.

TempPage and Page are the same element, just with two different variables pointing at it.

Any changes made via one variable will automatically happen to the other. To treat them differently, one would have to be a clone of the other. Node.cloneNode may be of use, but is not widely supported. You will need to make a deep copy.

There are two parts to your question and you are doing them both incorrectly.

  1. TempPage is the same object as Page . 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.
  2. Your attempts to get the h2 element are both incorrect.
    1. removeChild() won't work because:
      1. It requires a Node object, not a string.
      2. documentElement is the <html> element, but the <h2> element is a child of <body> , not <html> .
    2. getElementById() won't work because your <h2> element does not have an id attribute.

How you would do this is:

var TempPage = document.documentElement.cloneNode(true); // copy document
var h2 = TempPage.querySelector('h2'); // find h2 element
h2.parentNode.removeChild(h2);  // remove h2 element

If querySelector is not available, this will be a much more tedious task but still possible using normal DOM manipulation. You really need to learn about DOM manipulation

However from your complete code I can't fathom why you would need to clone the page. Just do this:

function textContent(node) {
    return node.textContent || node.innerText || '';
}
var h2 = document.getElementsByTagName('h2')[0];
var h2Text = textContent(h2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM