DOM 可以理解为document object model 文档对象模型。
DOM节点 分三类:
获取元素节点的方法
1.document.getElementById();
匹配唯一的元素节点。返回一个Object.
2.document.getElementsByTagName();
匹配元素节点名相同的元素,返回一个array数组. 也是Object
3.document.getElementsByClassName();
匹配类名相同的元素节点,返回的也是一个array数组.也是Object
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul id="big"> <li class="good"> <p class="good"></p> </li> <li class="notgood"></li> </ul><ul> <li class="good"> <p class="good"></p> </li> <li class="notgood"></li> </ul> <script> var idName = document.getElementById("big"); console.log(typeof idName); //object var className = document.getElementsByClassName("good"); console.log(className.length) //4 var tagName = document.getElementsByTagName("p"); console.log(tagName.length) //2 </script> </body> </html>
获取和设置属性
获取getAttribute,设置setAttribute
这两个属性不属于document方法,可以通过Object.来调用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <ul id="shop"> <li class="list"> <p title="apple">苹果</p> </li> <li class="list"> <p title="orange">橘子</p> </li> <li class="list"> <p >香蕉</p> </li> </ul> <script> var list =document.getElementsByTagName("p"); for(var i=0;i<list.length;i++){ var title = list[i].getAttribute("title"); if(title){ console.log(title); }else if(!title){ //可以赋值 list[i].setAttribute("title",'good'); } //可以做修改 if(title == "orange"){ list[i].setAttribute("title","full"); } } //apple orange null </script> </body> </html>