版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<style type="text/css">
#div1 {
width:300px;
height:300px;
border:1px solid red;
}
</style>
<button id="btn1">添加子元素到最前面</button>
<button id="btn2">添加子元素到最后面</button>
<div id="div1">
<a href="#" target="_self" title="呵呵" >点我啊</a>
</div>
<script type="text/javascript">
window.onload = function () {
var firstChild = document.getElementById('div1').firstChild;
document.getElementById('btn1').onclick = function () {
var btn = document.createElement('button');
btn.innerText = '哈哈';
document.getElementById('div1').insertBefore(btn, firstChild);//将子元素插入到指定元素的前面
};
document.getElementById('btn2').onclick = function () {
var btn2 = document.createElement('button');
btn2.innerText = '呜呜';
document.getElementById('div1').appendChild(btn2);//将子元素追加到最后面
};
};
</script>
</body>
</html>