HTML - DOM textContent 屬性



HTML DOM 的textContent屬性用於訪問和更新HTML元素及其所有子元素的文字內容作為一個單一字串。

訪問textContent時,它返回元素及其後代的組合文字,不包括任何HTML標籤。

語法

以下是HTML DOM 的textContent(訪問內容)屬性的語法:

element.textContent;

要使用新內容更新現有的HTML內容,請使用以下語法:

element.textContent = new_text;

其中new_text是用於更新元素內容的文字。

引數

此屬性不接受任何引數。

返回值

textContent屬性返回一個字串值,該值包含在HTML元素及其所有子元素中找到的所有文字。如果未找到文字,則返回'null'。

示例 1:更新文字內容

以下是HTML DOM textContent屬性的基本示例。它更新<h1>元素的文字內容:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM textContent</title>
<style>
   button{
      padding: 8px 10px;
   }
</style>
</head>
<body>
<h2>textContent Property</h2>
<p>Click the below button to change its text content..</p>
<h1 id="myHeading">Hello from Us</h1>
<button onclick="updateText()">Change Text</button>
<script>
   function updateText() {
      // Get the element by its ID
      var Us=document.getElementById('myHeading');
      // Update the text content
      Us.textContent='Welcome to Our Website';
   }
</script>
</body>
</html>  

上面的程式在單擊按鈕時更新“h1”元素的文字內容。

示例 2:顯示組合文字內容

以下是HTML DOM textContent屬性的另一個示例。我們使用此屬性來訪問和顯示<div>元素的組合文字內容,包括其所有子元素:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM textContent</title>
<style>
   button{
      padding: 8px 10px;
   }
</style>
</head>
<body>
<p>It displays the text content of div element.</p>
<div id="myDiv">
<p>This is a <span>paragraph</span> with 
<strong>strong</strong> emphasis.
</p>
</div>
<button onclick="displayText()">Display Text Content</button>
<p id="textContentDisplay"></p>
<script>
   function displayText() { 
      var ele=document.getElementById('myDiv');
      // Retrieve and display the text content
      var textcon = ele.textContent;
      document.getElementById('textContentDisplay').textContent = 'Text Content: ' + textcon;
   }
</script>
</body>
</html>

示例 3:檢查空內容

在下面的示例中,textContent屬性用於檢查<div>元素的文字內容。如果未找到文字內容,則顯示“未找到文字內容”。否則,它將顯示可訪問的文字內容:

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM textContent</title>
<style>
   button{
      padding: 8px 10px;
   }
</style>
</head>
<body>
<p>Checking for empty content..</p>
<div id="myDiv"></div>
<button onclick="checkContent()">Check Content</button>
<p id="contentStatus"></p>
<script>
   function checkContent() { 
      var ele=document.getElementById('myDiv');
      
      // Check if text content exists
      var textContent = ele.textContent;
      if (textContent === '') {
         document.getElementById
         ('contentStatus').textContent = 'No text content found.';
      } else {
        document.getElementById
        ('contentStatus').textContent = 'Text Content: ' + textContent;
      }
   }
</script>
</body>
</html>  

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
textContent
html_dom_element_reference.htm
廣告