HTML DOM Body 屬性


HTML DOM body 屬性與 HTML <body> 元素相關聯,用於設定或返回 <body> 元素的屬性值。它返回 <body> 元素。它可用於更改 <body> 元素中的內容。此屬性可以覆蓋 <body> 元素中顯示的子元素內容。

語法

以下是它的語法 −

設定 body 屬性 −

document.body = New_Content

在此,New_Content 是元素的新內容。

示例

我們來看一個 HTML DOM Body 屬性的示例 −

即時演示

<!DOCTYPE html>
<html>
<body>
<h2>Sample HEADING</h2>
<p>Click the below button to overwrite child content</p>
<button onclick="OverWrite()">Overwrite Content</button>
<p>A sample paragraph</p>
<script>
   function OverWrite() {
      document.body.innerHTML = "All the content inside the body tag is overwritten";
   }
</script>
</body>
</html>

輸出

它將生成以下輸出 −

單擊“Overwrite Content” −

在上面的示例中 −

我們在 <body> 元素中有許多元素,如 <h2> 元素、兩個 <p> 元素和一個按鈕。“Overwrite Content” 按鈕執行 OverWrite() 函式。

<button>Overwrite Content</button>

OverWrite() 函式獲取文件正文的 innerHtml 並將文字更改為“All the content inside the body tag is overwritten”。這樣就可以覆蓋 body 內部所有內容,基本上就是消除所有元素,僅顯示文字。

function OverWrite() {
   document.body.innerHTML = "All the content inside the body tag is overwritten";
}

更新時間:2021 年 2 月 20 日

89 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.