使用javascript附加div元素

时间:2015-09-29 08:28:55

标签: javascript html

我是jQuery的新手,我正在练习附加div元素。这是我的代码:

<!doctype html>
<html lang="en">
<head>
    <title>Div Id</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>

<script>
    document.body.onload = addElement;

    function addElement () { 
        // create a new div element 
        // and give it some content 
        var newDiv = document.createElement("div"); 
        var newContent = document.createTextNode("This is a first division"); 
        newDiv.appendChild(newContent); //add the text node to the newly created div. 

        // add the newly created element and its content into the DOM 
        var currentDiv = document.getElementById("div1"); 
        document.body.insertBefore(newDiv, currentDiv); 
    }
</script>

<body>
    <div id="div1">This is a second division.</div>
</body>
</html>

输出将是:

This is a second division.

但根据我的实现,输出应为

This is a first division
This is a second division.

我无法确定哪里出错了。请有人帮帮我。

提前致谢。

4 个答案:

答案 0 :(得分:1)

实际上它有效....尝试将你的javascript移动到你的html文件的头部

document.body.onload = addElement;

function addElement () { 
  // create a new div element 
  // and give it some content 
  var newDiv = document.createElement("div"); 
  var newContent = document.createTextNode("This is a first division"); 
  newDiv.appendChild(newContent); //add the text node to the newly created div. 

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 
}
<div id="div1">This is a second division.</div>

答案 1 :(得分:1)

onloadwindow对象的属性,而不是document.body对象的属性。

这有效:

window.onload = addElement;

答案 2 :(得分:0)

$('#div1').before('<div id=div0>This is a first division</div>')

demo

如果你想要Jquery,就像这样简单。

答案 3 :(得分:0)

如果您想使用jQuery,可以查看this fiddle

$('body').prepend('<div>This is a first division</div>');