HTML - DOM文件adoptNode()方法



HTML DOM adoptNode() 方法將一個節點從另一個文件中採用到當前文件中。所有節點都可以使用 adoptNode() 方法採用,包括父節點和子節點。

  • 使用 adoptNode() 方法時,節點及其子節點將從其原始文件中移除。
  • 節點的 ownerDocument 屬性將更改為當前文件。
  • 現在可以將已採用的節點插入到當前文件中。

語法

document.adoptNode(node);

引數

HTML DOM Document adoptNode() 方法接受單個引數,如下所示:

引數 描述
node 它代表您要從另一個 HTML 文件中採用的節點。

返回值

它返回從另一個文件中採用的節點物件。

HTML DOM Document adoptNode() 方法示例

以下示例演示了將 <h1> 從一個網頁 (**adoption.htm**) 移動到另一個網頁 (**adopted.htm**) 。

這是元素將被採用的頁面 (**adoption.htm**) 。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Adoption file</title>
</head>
<body>
    <h1>I am being adopted</h1>
    <h1>Welcome to TutorialsPoint</h1>
    <h1>This is adoptNode() method tutorial</h1>
</body>
</html>

在這個頁面 (**adopted.htm**) 中,將從不同的頁面採用元素。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>HTML DOM document adoptNode() Method</title>
</head>
<body>
    
    <iframe src="adoption.htm"  style="height: 400px; width: 400px"></iframe>
    <button onclick="fun()">Click me</button>
    <script>
        function fun(){
            let frame =document.getElementsByTagName("iframe")[0];
            let adopted_ele=frame.contentWindow.document.getElementsByTagName("h1")[0];
            let result=document.adoptNode(adopted_ele);
            document.body.appendChild(result);
        }
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
adoptNode() 是 1 是 12 是 1 是 3 是 12.1
廣告