此頁面由社群從英文翻譯而來。了解更多並加入 MDN Web Docs 社群。

View in English Always switch to English

Document:createTextNode() 方法

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.

建立一個新的 Text 節點。此方法可用於轉義 HTML 字元。

語法

js
createTextNode(data)

參數

data

包含要放入文字節點的資料的字串。

回傳值

一個 Text 節點。

範例

html
<button>是!</button>
<button>否!</button>
<button>我們可以!</button>

<hr />

<p id="p1">段落的第一行。</p>
js
function addTextNode(text) {
  const newText = document.createTextNode(text);
  const p1 = document.getElementById("p1");

  p1.appendChild(newText);
}

document.querySelectorAll("button").forEach((button) => {
  button.addEventListener("click", (event) => {
    addTextNode(`${event.target.textContent} `);
  });
});

規範

Specification
DOM
# ref-for-dom-document-createtextnode①

瀏覽器相容性