欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Dom操作html详细

程序员文章站 2024-03-20 09:28:46
...
                <p name='pn'>xxx</p>
		<p name='pn'>xxx</p>
		<p name='pn'>xxx</p>
		<p name='pn'>xxx</p>
		<ul>
			<li id="liID">子节点</li>
			<li>子节点1</li>
			<li id="delete">子节点2</li>
<li>前面的子节点将被删除 节点3</li>
</ul> <a id="aid" title="a标签的title">忘记我见过</a> <script> //ByName var nameA = document.getElementsByName('pn'); document.write("<br/>通过name获取元素" + nameA); nameA[0].innerHTML = "Hello"; //ByTagName var nameB = document.getElementsByTagName('p'); document.write("<br/>通过Tagname获取元素" + nameB); nameB[1].innerHTML = "Hello"; //获取元素属性 function getAttr() { var node = document.getElementById("aid"); var attr = node.getAttribute('title'); document.write("<br/>获取元素属性:" + attr); } getAttr(); //设置元素的属性 function setAttr() { var node = document.getElementById('aid'); node.setAttribute('href', 'http://www.baidu.com'); } setAttr(); //访问子节点 function getChildNode(){ var childNode = document.getElementsByTagName('ul')[0].childNodes; document.write("<br/>"+childNode.length); //空白也算入了节点 childNode[1].innerHTML= "第一个子节点增加"; } getChildNode();

  

//访问父节点
			function getParentNode() {
				var node = document.getElementById('liID');
				document.write("<br/>访问父节点:" + node.parentNode.nodeName);
			}
			getParentNode();
//创建节点
			function createNode() {
				var body = document.getElementsByTagName('body')[0];
				var btn = document.createElement("input");
				btn.type = 'button';
				btn.value = "按钮";
				document.write("<br/>");
				body.appendChild(btn);
			}
			createNode();
			
//添加节点
			function inserNode(){
				var parentNode = document.getElementsByTagName('ul')[0];
				var beforeNode = document.getElementById('liID');
				var newNode = document.createElement('li');
				newNode.innerHTML = "老子是刚加的";
				parentNode.insertBefore(newNode,beforeNode);
			}
			inserNode();
			
//删除节点
			function removeNode(){
				var parentNode = document.getElementsByTagName('ul')[0];
				var needMoveNode =document.getElementById('delete');
				parentNode.removeChild(needMoveNode);
			}
			removeNode();
//获取元素size
			function getSize(){
				var parentNode = document.getElementsByTagName('ul')[0];
				var width = parentNode.offsetWidth;
				var height =parentNode.offsetHeight;
				document.write("<br/>width"+width+"Height"+height);
			}
			getSize();