使用 insertBefore() 在特定位置附加子项时出错
error appending child at a specific location using insertBefore()
我正在尝试使用 insertBefore() 方法将 child 始终附加到 div 中的第二个位置,这给出了一个错误。
var j = document.createElement('div');
j.innerHTML = '<p>CreateElement example</p>'
document.insertBefore(j, document.querySelector('.test').children[1]);
<div class="test">
<div class="first">
<p>hello world</p>
</div>
<div class="second">
<p>lorem</p>
</div>
<div class="third">
<p>Lorem, ipsum dolor.</p>
</div>
</div>
错误:
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The
node before which the new node is to be inserted is not a child of
this node.
// First we find parent of elements
const parent = document.querySelector('.test');
// then create new div
var j = document.createElement('div');
// insert new div to parent
j.innerHTML = '<p>CreateElement example</p>'
parent.insertBefore(j, parent.childNodes[2]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<div class="test">
<div class="first">
<p>hello world</p>
</div>
<div class="second">
<p>lorem</p>
</div>
<div class="third">
<p>Lorem, ipsum dolor.</p>
</div>
</div>
</body>
</html>
我正在尝试使用 insertBefore() 方法将 child 始终附加到 div 中的第二个位置,这给出了一个错误。
var j = document.createElement('div');
j.innerHTML = '<p>CreateElement example</p>'
document.insertBefore(j, document.querySelector('.test').children[1]);
<div class="test">
<div class="first">
<p>hello world</p>
</div>
<div class="second">
<p>lorem</p>
</div>
<div class="third">
<p>Lorem, ipsum dolor.</p>
</div>
</div>
错误:
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
// First we find parent of elements
const parent = document.querySelector('.test');
// then create new div
var j = document.createElement('div');
// insert new div to parent
j.innerHTML = '<p>CreateElement example</p>'
parent.insertBefore(j, parent.childNodes[2]);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js" defer></script>
</head>
<body>
<div class="test">
<div class="first">
<p>hello world</p>
</div>
<div class="second">
<p>lorem</p>
</div>
<div class="third">
<p>Lorem, ipsum dolor.</p>
</div>
</div>
</body>
</html>