gpt4 book ai didi

javascript - 如何在另一个之前添加新的 div?

转载 作者:行者123 更新时间:2023-11-30 12:18:18 24 4
gpt4 key购买 nike

我想在 body 标签中的另一个 div 之前添加一个新的 div。我该怎么做?

html

<body class="variant-classic magazine notouch">
<div id="head" class="hfeed" tabindex="0">
<div id="header-container">
// other div areas
</body>

我写的脚本

var container = document.getElementById('header-container');
var conn = document.createElement('div');

conn.style.position='absolute';
conn.style.float='left';
conn.style.width='100%';
conn.style.height='50px';
conn.style.background='gray';

container.insertBefore(conn, container);

错误

 Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The       
node before which the new node is to be inserted is not a child of this node.

最佳答案

<div id="parentElement">
<span id="childElement">foo bar</span>
</div>

<script>
// Create a new, plain <span> element
var sp1 = document.createElement("span");

// Get a reference to the element, before we want to insert the element
var sp2 = document.getElementById("childElement");
// Get a reference to the parent element
var parentDiv = sp2.parentNode;

// Insert the new element into the DOM before sp2
parentDiv.insertBefore(sp1, sp2);
</script>

关于javascript - 如何在另一个之前添加新的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31786796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com