方法:
getElementsByName() 获取 name
getElementsByTagName() 获取元素
getAttribute() 获取元素属性
setAttribute() 设置元素属性
childNodes() 访问子节点
parentNode() 访问父节点
createElement() 创建元素节点
createTextNode() 创建文本节点
insertBefore() 插入节点
removeChild() 删除节点
offsetHeight() 网页尺寸
scrollHeight() 网页尺寸
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <title></title>
- </head>
- <body>
- <p name="pn">hello</p>
- <p name="pn">hello</p>
- <p name="pn">hello</p>
- <p name="pn">hello</p>
- <script>
- function getName(){
- //var count=document.getElementsByName("pn"); // 获取 name
- var count=document.getElementsByTagName("p"); // 获取元素
- alert(count);
- alert(count.length);// 拿到 4 个 p 元素
- var p=count[0];
- p.innerHTML="World";
- }
- getName();
- </script>
- <a id="aid" title="得到了 a 标签属性">hello</a>
- <script>
- function getAttr(){
- var anode=document.getElementById("aid");
- var attr=anode.getAttribute("title");// 获取元素属性, 可以把 title 换成 id
- alert(attr);
- }
- getAttr();
- </script>
- <br />
- <a id="aid2">aid2</a>
- <script>
- function setAttr(){
- var anode=document.getElementById("aid2");
- anode.setAttribute("title","动态设置 a 的 tiltle 属性");// 设置元素属性
- var attr=anode.getAttribute("title");
- alert(attr);
- }
- setAttr();
- </script>
- <br>
- <ul>
- <li>1</li>
- <li>2</li>
- <li>3</li>
- </ul>
- <script>
- function getChildNode(){
- var childnode=document.getElementsByTagName("ul")[0].childNodes;// 访问子节点
- alert(childnode.length); // 答案是 7, 是因为有空白项
- alert(childnode[1].nodeType);
- }
- getChildNode();
- </script>
- <br />
- <div id="div">
- <p id="pid">div 的 p 元素 </p>
- </div>
- <script>
- function getParentNode(){
- var div =document.getElementById("pid");
- alert(div.parentNode.nodeName); // 获取父节点
- }
- getParentNode();
- function createNode(){
- var body=document.body;
- var input=document.createElement("input");
- input.type="button";
- input.value="创建节点";
- body.appendChild(input);
- }
- 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[1]);// 删除节点
- }
- removeNode();
- function getSize(){ // 网页尺寸
- var height=document.body.offsetHeight||document.documentElement.offsetHeight;
- var width=document.body.offsetWidth;
- alert(width+","+height);
- }
- getSize();
- </script>
- </body>
- </html>
来源: http://www.bubuko.com/infodetail-2685814.html