请问各位关于js的问题

<html>
    <head>
        <title>home-page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width,initial-scale=1.0/">
        <style type="text/css">
            html,body,h1,h2,h3,h4,h5,h6,div,dl,dt,dd,ul,ol,li,blockquote,pre,p,hr,figure,table,caption,th,td,form,fieldset,legend,input,button,textarea,menu{margin:0;padding:0;}
            div{width: 200px; height: 300px;background-color: blue;display: inline-block;}
            .active{background-color: red;}
        </style>
    </head>
    <body>
        <div id="one" class="active"></div>
        <div id="two"></div>
        <div id="three"></div>
        <script type="text/javascript">
            document.getElementById("one").onclick=function(){
                document.getElementsByClassName("active")[0].className="";
                document.getElementById("one").className="active";
            }
            document.getElementById("two").onclick=function(){
                document.getElementsByClassName("active")[0].className="";
                document.getElementById("two").className="active"
            }
            document.getElementById("three").onclick=function(){
                document.getElementsByClassName("active")[0].className="";
                document.getElementById("three").className="active"
            }
        </script>
    </body>
</html>

请问大家在这段代码中若果使用document.getElementsByClassName("active").className="";
把[0]去掉则会active这个类名这不会变换颜色

阅读 2.3k
3 个回答

不明白你想问什么getElementsByClassName的返回值就是一个数组,无论获取到了0个,1个或是多个。

js的getElementsByClassName('xxx')方法返回的是一个类数组NodeList,结构与数组类似,
其中每一项保存着一个class为xxx的节点;
不加索引document.getElementsByClassName("active").className是改变不了calss的,因为document.getElementsByClassName("active")对象没有属性className;
只有具体节点document.getElementsByClassName("active")[i]才有属性className。

返回的是个HTMLCollection类数组对象。
不加索引相当于对整个对象操作,就好比arr[0]和arr的区别。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题