zoukankan      html  css  js  c++  java
  • 节点访问关系

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title>Document</title>
        <style>
            #father{
                300px;
                height:300px;
                margin:100px auto;
                background-color: gray;
            }
            #father div{
                300px;
                height:50px;
                background-color: blue;
                margin:10px 0;
            }
        </style>
        <script>
            window.onload=function()
            {
                var kid=document.getElementById("kid");
    
                //父节点
                var father=kid.parentNode;
                father.style.backgroundColor="pink";
    
                //下一个兄弟节点
                var brother=kid.nextElementSibling||kid.nextSibling; //下一个兄弟节点,兼容性写法,正常浏览器要写在前面
                brother.style.backgroundColor="pink";
    
                //上一个兄弟节点
                var kid2=document.getElementById("kid2");
                var brothershang=kid2.previousElementSibling||kid2.previousSibling;
                brothershang.style.backgroundColor="pink";
    
                //子节点,第一个孩子
                var father=document.getElementById("father");
                var kid1=father.firstElementChild||father.firstChild;
                kid1.style.backgroundColor="green";
    
                //子节点,最后一个孩子
                var kidlast=father.lastElementChild||father.lastChild;
                kidlast.style.backgroundColor="green";
                
                //孩子节点,所有的孩子
                var kidall=father.children;  //children常用,childNodes不常用
                for(var i=0;i<kidall.length;i++)
                {
                    if(kidall[i].nodeType==1)       //因为换行也是节点,所有需要利用nodeType==1,获取元素节点,改变所有孩子的背景颜色,否则换行节点没有背景颜色会报错
                    {
                        kidall[i].style.backgroundColor="orange";
                    }
                }
    
    
            }
        </script>
    </head>
    <body>
    <div id="father">
        <div id="kid"></div>
        <div id="kid2"></div>
        <div></div>
        <div></div>
        <div></div>
    </div>
    </body>
    </html>
    

      

  • 相关阅读:
    第六次学习笔记
    第四篇笔记
    第三篇学习笔记
    第二篇学习笔记
    第一篇学习笔记
    px与dp、sp之间的转换
    SQLite的使用(二):数据增删改查
    Logcat的级别以及Logcat的调试使用
    Android 创建服务(一)
    简说SQLite
  • 原文地址:https://www.cnblogs.com/shanlu0000/p/11203639.html
Copyright © 2011-2022 走看看