Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

javascript - Can't appendChild to a node created from another frame

I have a page with an iframe and would like to extract a DOM node from the child frame and put it on the parent page. This works in Firefox (3.5), but not in Internet Explorer (7).

I've broken down the code to the simplest I can.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html>
<head>
<title>Fragment</title>
</head>

<body>

<iframe src="blank.html"></iframe>

<script type="text/javascript">
window.onload = function () {
    var fragment = document.createDocumentFragment();
    var div = frames[0].document.createElement("div");
    fragment.appendChild(div);
};
</script>

</body>
</html>

I get an error "Invalid argument" on the "fragment.appendChild(div);" line. The error seems to stem from the fact that I'm creating the document fragment from the iframe's document and the div element from the parent document. This code works if both use the same document.

I want to keep any events that might be attached to the DOM nodes, so I don't want to use innerHTML.

Anyone know a fix for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your problem is that you are not adopting the nodes into the fragment that are created in the current document. Use either the following:

fragment.appendChild(fragment.ownerDocument.createElement("div"));

or

fragment.appendChild(fragment.ownerDocument.adoptNode(document.createElement("div"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...