createElement 创建DOM元素

时间:2021-08-15 07:43:19
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
window.onload=function (){
var $ = function(id){
return document.getElementById(id);
} var oBtn=$('btn1');
var oTxt=$('txt1');
var oUl=$('ul1');
var aLi=oUl.getElementsByTagName('li'); oBtn.onclick=function (){
//用DOM方法创建出来的元素,和普通元素没有任何区别
var oLi=document.createElement('li'); oLi.innerHTML=oTxt.value; //oUl.appendChild(oLi); 用此句会添加到最后,下面会添加到最前面
if(aLi.length>0){
oUl.insertBefore(oLi, aLi[0]); // insertBefore(节点,在谁之前插入)
}
else{
oUl.appendChild(oLi); // 用法: appendChild(节点);
}
};
};
</script>
</head>
<body>
<input id="txt1" type="text" />
<input id="btn1" type="button" value="创建Li" />
<ul id="ul1"> </ul>
</body>
</html>

Document类型定义了创建Element和Text对象的方法,Node类型定义了在节点树中插入、删除和替换的方法。

 // 从指定的URL,异步加载和执行脚本
function loadasync(url){
var head = document.getElementsByTagName('head')[0]; //查找文档的<head>标签
var s = document.createElement('script'); //创建一个<script>元素
s.src = url; //设置它的src属性值
head.appendChild(s);
}