JavaScript-DOM(2)
DOM节点(2)
1)首尾子节点
--有兼容性问题
--firstChild、firstElementChild---第一个子节点
--lastChild、lastElementChild---最后一个子节点
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 <script> 7 window.onload = function (){ 8 var oUl = document.getElementById('ul1'); 9 //oUl.firstChild.style.background = 'red'; 10 //var first = oUl.firstChild||firstElementChild;//解决兼容性问题 11 oUl.firstElementChild.style.background = 'red'; 12 13 14 } 15 </script> 16 </head> 17 18 <body> 19 <ul id="ul1"> 20 <li>aaaaaa</li> 21 <li>bbbbbb</li> 22 <li>ccccccc</li> 23 <li>ddddddd</li> 24 </ul> 25 </body> 26 </html>
运行效果:
2)兄弟节点
--有兼容性问题
--nextSibling、nextElementSibling---
--previousSibling、previousElementSibling--
代码:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 <script> 7 window.onload = function (){ 8 9 oLi = document.getElementById('li1'); 10 //oLi.previousSibling.style.background = 'blue'; //有兼容性问题 11 oLi.previousElementSibling.style.background = 'blue'; 12 } 13 </script> 14 </head> 15 16 <body> 17 <ul id="ul1"> 18 <li>aaaaaa</li> 19 <li id="li1">bbbbbb</li> 20 <li>ccccccc</li> 21 <li>ddddddd</li> 22 </ul> 23 </body> 24 </html>
运行效果:
aaaaa