js创建节点

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cheng_cuo_tuo/article/details/86657161
<script>
/*
	createElement()方法可以根据参数指定的名称创建一个新的元素节点,并返回新建元素节点对象。
	是Document对象的一个方法。
*/
window.onload = function() {
	var p = document.createElement("p");
	var info = "nodeName: " + p.nodeName;
	info += ", nodeType: " + p.nodeType;
	alert(info);//nodeName: P, nodeType: 1
	document.body.appendChild(p);
}

/*
		值得注意的是,createElemet()方法创建的新节点元素,不会自动添加到文档结构中,此节点话没有nodeParent属性,
	它只是存储在内存中的DocumentFragment对象,该对象仅在js的上下文中有效。
		需要使用appenChile()、insertBefore()、replaceChild()方法实现。
*/
</script>
<script>
/*
	createTextNode()方法,可以为新建或已经存在的元素中插入文本内容,返回一个只从新建文本节点的引用。
	var txt = document.createTextNode("text");
	参数中不能包含任何的HTML标签,否则js会把这些标签作为字符串进行显示。
*/
window.onload = function(){
	var txt = document.createTextNode("Hello World");
	var info = "nodeName: " + txt.nodeName;
	info += ", nodeType: " + txt.nodeType;
	alert(info);//nodeName: #text, nodeType: 3
}
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script>
window.onload = function(){
	var p = document.createElement("p");
	var h1 = document.createElement("h1");
	var txt = document.createTextNode("Hello World");
	p.appendChild(txt);
	h1.appendChild(p);
	document.body.appendChild(h1);	
	//在创建树
}
</script>
</head>

<body>
<!--
	<h1>
		<p>Hello World</p>
	</h1>
-->
</body>

猜你喜欢

转载自blog.csdn.net/cheng_cuo_tuo/article/details/86657161