javascript - 使用 javascript dom 在 HTML 中插入 Cite 元素
问题描述
我想在 HTML 中存在但为空的页脚标签中添加一个带有文本和 href 的引用元素(当前)
我正在使用此代码,但它不起作用。
let cite = document.createElement("cite");
cite.setAttribute("text","Information and photos from Wikipedia");
cite.setAttribute("href", "https://en.wikipedia.org/wiki/Bumblebee");
let ftr = document.getElementsByTagName('footer')[0];
ftr.innerHTML(cite);
我希望插入 dom 元素的 HTML 页面的代码是
<!DOCTYPE html>
<html lang="en">
<!-- DO NOT MODIFY THIS FILE OTHER THAN REFERENCING THE SCRIPT FILE -->
<head>
<meta charset="UTF-8">
<title>Assignment 5a</title>
<link href="style.css" rel="stylesheet" />
</head>
<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 beast".</p>
<h2>Distribution and habitat</h2>
<figure><img src="bee2.jpg" />
<figcaption>Cuckoo bumblebees have similar warning coloration to
nest-making bumblebees.</figcaption>
</figure>
<p>Bumblebees t pollinators.</p>
</main>
<footer>
</footer>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
请注意,我不能在 JS 文件和 document.write 中使用 HTML 标签
解决方案
你很亲密。
此示例用于cite.textContent =
设置元素的内容,cite
而不是设置名为“text”的属性。
它还用于ftr.appendChild(cite)
将cite
元素添加到ftr
页脚元素。这是因为innerHTML
不采用 DOM 元素,而是采用 HTML 字符串。所以ftr.innerHTML = '<span>hello world</span'
会起作用,但ftr.innerHTML = cite
不会。
let cite = document.createElement("cite");
cite.textContent = "Information and photos from Wikipedia";
cite.setAttribute("href", "https://en.wikipedia.org/wiki/Bumblebee");
let ftr = document.getElementsByTagName('footer')[0];
ftr.appendChild(cite);
<!DOCTYPE html>
<html lang="en">
<!-- DO NOT MODIFY THIS FILE OTHER THAN REFERENCING THE SCRIPT FILE -->
<head>
<meta charset="UTF-8">
<title>Assignment 5a</title>
<link href="style.css" rel="stylesheet" />
</head>
<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 beast".</p>
<h2>Distribution and habitat</h2>
<figure><img src="bee2.jpg" />
<figcaption>Cuckoo bumblebees have similar warning coloration to nest-making bumblebees.</figcaption>
</figure>
<p>Bumblebees t pollinators.</p>
</main>
<footer>
</footer>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
推荐阅读
- node.js - 使用 Jasmine Hook 捕获测试套件的总时间或持续时间
- php - 如何在基本身份验证中显示错误消息?
- reactjs - 获取错误“从 fetchData 返回的承诺被忽略”
- c++ - 如何在一个文件中注册 mutli LLVM Pass?
- spring-boot - Spring oauth2 AuthorizationServer 不重定向
- angular - 找不到“object”类型的不同支持对象“[object Object]”。NgFor 仅支持绑定到 Iterables,例如 Angular 8 中的数组
- java - 为单个 kafka 主题创建多个消费者
- spring-boot - Spring Boot & reactor-netty https 多个域
- java - TestNG 套件并行化 testNG xml + Gradle
- go - 可靠地捕获外部命令的输出