<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JsDOM对象</title> <script type="text/javascript" src="tzy.js"></script> </head> <body> <p name = "pn">hello</p> <p name = "pn">hello</p> <p name = "pn">hello</p> <p name = "pn">hello</p> <a id = "aid" title = "title属性"></a> <ul><li id="li1">1</li><li>2 3</li><li>3</li></ul> <div id="div"> <p id="pid">我是p节点</p> <p id="pid1">我是p1节点</p> </div> <script> function getName() { var count = document.getElementsByName("pn");//根据name获取 alert("count长度"+count.length);//看是否获取到 var p = count[2]; p.innerHTML = "world"; var count1 = document.getElementsByTagName("p");//根据标签名获取 alert("count1长度"+count1.length); var p1 = count1[3]; p1.innerHTML = "hahaha"; } getName(); function getSetAttr() { var a = document.getElementById("aid");//根据id获取 var attr = a.getAttribute("title");//获取当前元素某个属性值 alert(attr); a.setAttribute("id","动态被设置为id")//设置当前元素某个属性值 var attr1 =a.getAttribute("id"); alert(attr1); } getSetAttr(); function getChildNode(){ var childnode = document.getElementsByTagName("ul")[0].childNodes;//获取子节点项,注意ul里面空格也会算子节点,所以要去掉空格 alert("ul的字节点数"+childnode.length); alert("ul里的第一个子节点类型"+childnode[0].nodeType);//有疑问 alert("ul里的第二个子节点类型"+childnode[1].nodeType); } getChildNode(); function getParentNode() { var li1 = document.getElementById("li1"); alert("li1的父节点"+li1.parentNode.nodeName);//获取父节点及名字 } getParentNode(); function createNode(){ var body = document.body;//获取body var input = document.createElement("input");//创建节点 input.type = "button"; input.value = "自建按钮"; body.appendChild(input);//将节点添加到body中 //createTextNode()添加文本节点 } createNode(); function addNode() { var div = document.getElementById("div"); var node = document.getElementById("pid"); var newnode = document.createElement("p"); newnode.innerHTML = "这是我添加的p节点"; div.insertBefore(newnode,node);//添加节点到某个节点前 } addNode(); function removeNode() { var div = document.getElementById("div"); var p = div.removeChild(div.childNodes[2]);//删除p节点因为空格算一个节点 } removeNode(); function getSize(){ //offsetheight 网页尺寸(不包含滚动条) //scrollheight 网页尺寸(包含滚动条) var height = document.body.offsetHeight||document.documentElement.offsetHeight;//兼容性写法 var width = document.body.offsetWidth; alert("宽度"+width+"高度"+height); } getSize(); </script> </body> </html>
时间: 2024-10-17 20:43:53