HTML - DOM 元素 outerText 屬性



**outerText** 屬性允許您訪問或更新 HTML 元素的文字內容,包括其所有巢狀文字和元素。

語法

設定 outerText 屬性值
node.outerText = text;
獲取 outerText 屬性值
node.outerText;

屬性值

描述
文字 您要設定的文字內容。

返回值

當訪問時,outerText 屬性返回一個包含元素及其所有巢狀文字和元素的組合文字的字串。

設定 outerText 屬性時,它不返回任何值。

HTML DOM 元素 'outerText' 屬性示例

以下是一些顯示 'outerText' 屬性用法的示例,以便更好地理解。

用新文字替換當前文字

此示例顯示了 outerText 屬性的用法。它包含一個包含文字的**<div>** 元素和**<p>** 元素。當單擊按鈕時,它會將 outerText 屬性設定為一個新字串,用新文字替換其所有當前內容。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>
        HTML DOM Element outerText Property
    </title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>outerText Property</h2>
    <h4>Click button to replace current 
    	text with new one.. 
    </h4><hr>
    <div id="exDiv">
        <p>This is some initial content.</p>
    </div>
    <br>
    <button onclick="changeText()">Change Text</button>

    <script>
        function changeText() {
            var ediv=document.getElementById('exDiv');
            ediv.outerText = 
            "This text has been replaced.";
        }
    </script>
</body>

</html>  

訪問 Div 元素的當前內容

此示例使用 outerText 屬性訪問**<div>** 元素以顯示其當前文字內容。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>Accessing outerText</title>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>outerText Property</h2>
    <h4>Click button below to display the 
    	current content.. 
    </h4><hr>

    <div id="exampleDiv">
        This is the current content.
        <p>Paragraph content.</p>
    </div>

    <hr>
    <button onclick="displayText()">
        Display Text
     </button>
    
    <div id="ot"></div>

    <script>
        function displayText() {
            var exDiv = document.getElementById('exampleDiv');
            var textContent = exDiv.outerText;

            // Display the outerText in the output div
            var otDiv = document.getElementById('ot');
            otDiv.textContent = textContent;
        }
    </script>
</body>

</html>    

支援的瀏覽器

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