首页 > 解决方案 > 在现有元素之间添加元素

问题描述

我目前正在学习 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>

指令是

  1. 使用该insertBefore方法在名称列表中添加一个新元素,
  2. 在名称之间添加一个Bob元素Cesar

我想在 和'bobby'之间插入名字BobCesar

到目前为止,这是我的代码,但我不知道如何正确格式化它:

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

标签: javascripthtmlnodes

解决方案


我认为代码是这样的

这是我正在关注的文档

这是一个片段

// 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>


推荐阅读