第一种创建方法(页面加载完成后,页面代码将会被覆盖)
<!DOCTYPE html><html lang="en"><head> ?<meta charset="UTF-8"> ?<title>title</title></head><body><input type="button" value="创建一个p" id="btn"/>娃哈哈
<div id="dv"></div><script> ?//document.write("标签代码及内容");
my$("btn").onclick=function () {
document.write("<p>这是一个p</p>");
};
?my$("btn").onclick=function () { ???document.write("<p>这是一个p</p>"); ?}; // document.write("<p>这是一个p</p>"); ?//document.write()创建元素,缺陷:如果是在页面加载完毕后,此时通过这种方式创建元素,那么页面上存在的所有的内容全部被干掉</script></body></html>
第二种创建的方式
<script> ?//点击按钮,在div中创建一个p标签 ?//第二种方式创建元素: 对象.innerHTML="标签代码及内容"; ?my$("btn").onclick=function () { ???my$("dv").innerHTML="<p>窗前明月光,疑是地上霜,举头望明月,低头思故乡</p>"; ?};</script>
第三种创建的方式
//第三种方式创建元素 ?//创建元素 ?//document.createElement("标签名字");对象 ?//把元素追加到父级元素中 ?//点击按钮,在div中创建一个p ?my$("btn").onclick = function () { ???//创建元素的 ???var pObj = document.createElement("p"); ???setInnnerText(pObj, "这是一个p"); ???//把创建后的子元素追加到父级元素中 ???my$("dv").appendChild(pObj); ?}; //设置任意元素的中间的文本内容 function setInnnerText(element,text) { if(typeof element.textContent=="undefined"){ element.innerText=text; }else{ element.textContent=text; } }
js中标签的创建
原文地址:https://www.cnblogs.com/liushisaonian/p/9343713.html