我想在body标签的另一个div之前添加一个新的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.
@ᔕᖺᘎᕊ对不起类型的错误。 –
一个元素不能是它自己的孩子。第二个参数是要在其之前添加新元素的引用元素,它必须是具有调用的“insertBefore”方法的元素的子元素。在你的情况下,你可能需要'document.body.insertBefore(conn,container);' – Teemu
@Teemu那么,如何添加新的div呢? –