使用 JavaScript 更改标题元素的文本

使用 textContent 属性更改标题元素的文本,例如 heading.textContent = 'Replacement heading text'。 textContent 属性会将标题文本设置为提供的字符串,替换任何现有内容。

以下是本文示例的 HTML。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <h1 id="heading">Initial heading text</h1>

    <script src="index.js"></script>
  </body>
</html>

这是相关的 JavaScript 代码。

const heading = document.getElementById('heading');

// ✅ Change (replace) the text of the element
heading.textContent = 'Replacement heading text';

// ✅ Change (replace) the content with HTML
heading.innerHTML = `<span style="background-color: yellow">Replacement HTML</span>`;

// ✅ Append / Prepend text to the element
heading.insertAdjacentText('beforeend', ' appended text');

// ✅ Append / Prepend HTML to the element
heading.insertAdjacentHTML(
  'beforeend',
  `<span style="background-color: lime"> appended HTML</code>`,
);

我们使用 h1 元素上的 textContent 属性来更改其文本内容。

textContent 属性还可用于读取元素及其后代的文本内容。

在元素上设置 textContent,删除元素的所有子元素,并将它们替换为具有提供的字符串的单个文本节点。

如果需要完全替换标题的 HTML 内容,请使用 innerHTML 属性。

const heading = document.getElementById('heading');

// ✅ Change (replace) the content with HTML
heading.innerHTML = `<span style="background-color: yellow">Replacement HTML</span>`;

innerHTML 属性获取或设置元素中包含的 HTML。

通过在元素上设置属性,您可以有效地替换以前包含在 h1 元素中的 HTML。

在设置元素的 HTML 时,我们不应该在不转义的情况下使用用户生成的数据。 这将使我们的应用程序容易受到 XSS 攻击。

如果我们需要向 h1 元素的现有内容追加或前置文本,请使用 insertAdjacentText 方法。

const heading = document.getElementById('heading');

// ✅ Append / Prepend text to the element
heading.insertAdjacentText('beforeend', ' appended text');

insertAdjacentText 方法采用以下 2 个参数:

  1. position – 相对于应插入文本的元素的位置。 可以是以下4种之一:
  • beforebegin – 在元素本身之前。
  • afterbegin – 就在元素内部,在第一个子元素之前。
  • beforeend – 就在元素内部,在最后一个子元素之后。
  • afterend – 在元素本身之后。
  1. data – 用于创建要插入到给定位置的新文本节点的字符串。

我们将文本插入到 h1 元素的最后一个子元素之前,但我们可以根据用例更改位置参数的值。

如果需要在标题中插入 HTML,请使用 insertAdjacentHTML 方法。

const heading = document.getElementById('heading');

// ✅ Append / Prepend HTML to the element
heading.insertAdjacentHTML(
  'beforeend',
  `<span style="background-color: lime"> appended HTML</code>`,
);

insertAdjacentHTML 方法采用的第一个参数与 insertAdjacentText 相同 – 应该插入 HTML 的位置。

第二个参数是包含要插入的内容的 HTML 字符串。

请注意 ,此方法不应在未转义的情况下与用户提供的数据一起使用。 这将使我们的应用程序容易受到跨站点脚本攻击。