首页 > 解决方案 > 使用 javascript 在正文的第一段之前插入一个新的 h3 元素

问题描述

我想仅使用 javascript 在 HTML 的第一段之前插入一个新的 h3 元素,其中包含我的名字。我不想为它编辑 HTML 文件或 CSS 文件。我已经在 javascript 文件中尝试过这段代码

let h3e = document.createElement("h3");
h3e.textContent("Student Name");
document.body.insertBefore(h3e, document.body.firstChild);

但它不工作

let h3e = document.createElement("h3");
h3e.textContent("Student Name");
document.body.insertBefore(h3e, document.body.firstChild);
<body>
      <header>
        <h1>Bumblebee</h1>
      </header>

      <main>
        <h2>General description</h2>

        <figure><img src="bee1.jpg" />
          <figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
          </figcaption>
        </figure>

        <p>Bumblebees vary in o about 40 mm longginger beast".</p>

          <h2>Distribution and habitat</h2>

    <p>Test data</p>
</body>

标签: javascript

解决方案


你的问题在这里

h3e.textContent("Student Name");

// Error msg: "Uncaught TypeError: h3e.textContent is not a function",

改成

var t = document.createTextNode("Student Name");
h3e.appendChild(t);

或@Paul Rooney 的评论:

h3e.textContent ="Student Name";

完整代码和演示在这里:

var h3e = document.createElement("H3");
var t = document.createTextNode("Student Name");
h3e.appendChild(t);

document.body.insertBefore(h3e, document.body.firstChild);
<body>
      <header>
        <h1>Bumblebee</h1>
      </header>
      <main>
        <h2>General description</h2>
        <figure><img src="bee1.jpg" />
          <figcaption>A common bumblebee extending its tongue towards a Heuchera inflorescence.
          </figcaption>
        </figure>
        <p>Bumblebees vary in o about 40 mm longginger beast".</p>
          <h2>Distribution and habitat</h2>
    <p>Test data</p>
</body>


更详细地阅读此线程: TextNode 或 textContent?

在此处输入图像描述


推荐阅读