2015-08-03 62 views
1

我想在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. 
+0

@ᔕᖺᘎᕊ对不起类型的错误。 –

+0

一个元素不能是它自己的孩子。第二个参数是要在其之前添加新元素的引用元素,它必须是具有调用的“insertBefore”方法的元素的子元素。在你的情况下,你可能需要'document.body.insertBefore(conn,container);' – Teemu

+0

@Teemu那么,如何添加新的div呢? –

回答

1

首先,请关闭所有div

看看这个fiddle

函数.insertBefore()将应用于父元素。

以下是摘录。因为你已经设置position=absolute,因此,文字隐藏在背后div

var parent = document.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'; 
 

 
parent.insertBefore(conn, container);
<body class="variant-classic magazine notouch"> 
 
    <div id="head" class="hfeed" tabindex="0"></div> 
 
    <div id="header-container"></div> 
 
    // other div areas 
 
</body>

文本// other div areas不是新div插入后可见。

+0

在Google博客代码中,body没有id。如何解决这个问题? –

+0

然后它变得更加容易。 'var parent = document.body;'。我已经更新了我的答案。 –

1
<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> 
+0

以上是否有意义理解insertBefore()? –

0

如果你想插入一组Node对象或DOMString对象,你可以考虑使用父节点的第一个孩子之前:

parentElement.prepend(newFirstChild); 

你的情况,这将是:

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.prepend(conn); 

这是ES7的新增功能。它目前可用于Chrome,FireFox和Opera。

传送者应该能够处理它,直到它变得可用。

更多信息:Link

希望它可以帮助...

1
var txt3 = document.createElement("div"); 

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

$("#head").wrap(txt3); 
相关问题