【发布时间】:2021-06-18 19:19:42
【问题描述】:
我只想通过使用 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>
【问题讨论】:
-
如果你查看开发控制台,你会看到一个错误。错误是
h3e.textContent不是函数。您应该只分配给它而不是调用它。即h3e.textContent ="Student Name";. -
我希望“学生姓名”显示在
大黄蜂在 o 约 40 毫米长的野兽中变化。
标签 -
您只需要使用
document.querySelector('p')找到段落节点并在此之前插入。不过,您的示例中未关闭的标记可能会导致问题。 -
var h3e = document.createElement("H3"); var t = document.createTextNode("学生姓名"); h3e.appendChild(t); document.body.insertBefore(h3e, document.querySelector("main > p") );查询选择器不起作用。
标签: javascript