javascript - 使用 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>
解决方案
你的问题在这里
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?
推荐阅读
- mysql - RDBMS 中具有 OR 条件的 Row_number 函数
- apache-spark - Pyspark 以高性能的方式将多个有序数据流选择到一个 RDD 中
- python - Django 日志记录 - 登录 ValidationError 不起作用
- ios - 表单内的 TableView 没有正确显示 Swift
- r - Passing list of characters into file.path in R
- python - 基于索引映射和映射到同一索引的平均值将值从一个张量复制到另一个张量
- android - 如何在 Android Studio 3.6.0 中禁用 zipfinger 打包工具
- xml - Postgres 到 xml 排序依据
- css - 如何使引导列可滚动?
- r - 如何从ggplot中的条形顺序单独自定义图例的顺序?