2010-12-03 41 views
6

我已經在這裏工作了幾個小時,現在即將開始剝離頭髮。基本上我需要做的是獲取出現在主體中的第一個元素,然後在其之前插入另一個元素。從<body>獲取第一個元素,然後insertBefore()

我已嘗試以下沒有成功(未定義或爲空)來獲得的第一個元素

window.document.body.firstChild 

document.getElementsByTagName("body").firstChild 

document.getElementsByTagName("body")[0].firstChild 

window.document.documentElement.childNodes[1].childNodes[0] 

和以往的片段的混合和匹配嘗試的整體轉換。我也嘗試過只獲取body,然後appendChild()也沒有成功。

這裏的任何幫助表示讚賞。提前致謝。

+0

是它在iframe,或正常文件? – danjah 2010-12-03 02:16:41

+1

`document.body.firstChild`很好。你確定你的`insertBefore()`參數的順序是正確的嗎? – 2010-12-03 02:22:53

回答

2

你想是這樣的:

var first = document.body.children[0]; 
var beforeEle = document.createElement("div"); 
beforeEle.innerHTML = "I'm the first element in the body!"; 
document.body.insertBefore(beforeEle, first); 
12

是,document.body.firstChild是正確的。您很可能忽略了這樣的事實:insertBefore是父元素的一種方法,並且它在現有元素之前採用新元素。例如:

var addedElement = document.createElement('p'); 
addedElement.appendChild(document.createTextNode('Hello, world!')); 

var body = document.body; 
body.insertBefore(addedElement, body.firstChild); 
1

最好的解決方案,以預先考慮到身體我所能了一個元件是一個班輪:

document.body.insertBefore(element, dom.document.body.firstChild) 
相關問題