javascript - 在现有元素之间添加元素
问题描述
我目前正在学习 HTML 和 JavaScript,但我无法理解节点/元素以及如何使用它们。我正在参加一个在线课程,该课程使用机器人更正我的代码。这是我的 HTML 文件中所需的内容:
<body>
<section id="players">
<h1>Players</h1>
<ol>
<li>Alice</li>
<li>Bob</li>
<li>Cesar</li>
</ol>
</section>
<script src="index.js"></script>
</body>
指令是
- 使用该
insertBefore
方法在名称列表中添加一个新元素, - 在名称之间添加一个
Bob
元素Cesar
我想在 和'bobby'
之间插入名字Bob
Cesar
到目前为止,这是我的代码,但我不知道如何正确格式化它:
const textnode = document.createTextNode('bobby')
const node = document.createElement('LI')
node.insertBefore()
node.appendChild(textnode)
document.getElementById('players').appendChild(node)
机器人的输出是:
index.js
✓ exists
✓ is valid JavaScript
✓ adds a list item
✓ makes it so that the first list item contains “Alice”
✓ makes it so that the second list item contains “Bob”
1) makes it so that the fourth list item contains “Cesar”
✓ uses insertBefore
解决方案
我认为代码是这样的
这是我正在关注的文档
这是一个片段
// create a li element
const node = document.createElement('li')
// insert the name bobby as innerHtml value of li node
node.innerHTML = 'bobby'
// get the ol element
const list = document.querySelector('#players ol')
// get all the list items under ol
const items = document.querySelectorAll('#players ol li')
// from what we know, cesar is that last element on the list
const cesar = items[items.length - 1]
// we got all we need the node that we wanted to insert
// the list item where we want the node to be inserted before
// and the ol list element which holds to be the parent of them all
// So we insert it.. using the syntax below
const inserted = list.insertBefore(node, cesar)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<section id="players">
<h1>Players</h1>
<ol>
<li>Alice</li>
<li>Bob</li>
<li>Cesar</li>
</ol>
</section>
</body>
</html>
推荐阅读
- mysql - 通过 cmd 将大型数据库导入 mysqlAdmin 时出错
- deep-learning - 使用 pytorch 训练神经网络时损失的周期性模式
- .net - 使用 LoggerFactory 登录 Application Insights for .NET Core 2.1 控制台应用程序
- popup - 关闭对话框后Appium找不到任何元素
- javascript - Javascript为不同的div加载具有特定功能的php文件
- java - 如何从 Future 中获取价值
在 Java REST API 中 - javascript - 尝试使用 vanilla Javascript 创建动态表,代码不起作用
- php - 如何使用 DynamoDb 中的地图更新列表中的项目?
- python - 在 get_data(request) 中渲染多个模板
- azure-devops - 错误显示为无父