3 回答
TA贡献1864条经验 获得超6个赞
const textnode = document.createTextNode('bobby');
const node = document.createElement('LI');
const ol = document.getElementsByTagName("OL")[0];
node.appendChild(textnode)
ol.insertBefore(node,ol.children[2]);
console.log("This is the content of ol.children:");console.log(ol.children);
console.log("Now if you want to delete Bob, look at his index")
ol.removeChild(ol.children[1]);
<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>
TA贡献1943条经验 获得超7个赞
我认为代码是这样的
这是我关注的文档
这是一个片段
// 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>
TA贡献1808条经验 获得超4个赞
inserBefore() 方法需要两个参数作为输入。首先是要插入的节点,其次是必须之前插入要追加的节点的节点。
因此,您需要选择该元素中的第三个节点。然后在节点上调用该方法,并在列表中的第三个节点之前插入新节点。<ol>insertBefore<ol>
// Get the <ol> element
const listNode = document.querySelector('#players ol');
// Get the third <li> in the <ol> element.
const thirdListItem = listNode.children[2];
// Create the new node.
const textnode = document.createTextNode('bobby');
const node = document.createElement('LI');
node.appendChild(textnode);
// Now insert the new node in the <ol> before the third <li>
listNode.insertBefore(node, thirdListItem);
添加回答
举报