在另一个div javascript中定位div

时间:2015-02-21 19:12:02

标签: javascript

我需要用javascript(没有Jquery,尝试首先学习原始Javascript)来定位另一个div中的div。说我有一组3个div,名为" outerSquare1"," outerSquare2"等等,每个都有一个内部div,名为" innerSquare" (未编号)。

如何通过Javascript在稍后的点上定位特定div的内部正方形。我想做这样的事情,但显然不行。

outerSquare2.innerSquare.style.width="100px";

或者这个

foo = outerSquare3.getElementById("innerSquare");
foo.style.width="100px";

JSFiddle

2 个答案:

答案 0 :(得分:0)

当您需要对一些类似的HTML元素进行分组时,您应该使用.class而不是#id。当您使用它时,您可以使用node#querySelector(selector)方法返回与选择器匹配的嵌套节点。有一些例子,你如何做到这一点:

http://jsfiddle.net/r866bnwu/8/

答案 1 :(得分:0)

您可以使用返回DOM元素子项列表的childNodes属性。这是一个例子。希望这有帮助。

    <html>
    <style>
        #outerDiv{
            height:150px;
            width:150px;
            background-color:yellow;
        }

        .innerDiv{
            position:relative;
            height:20px;
            width:50px;
            top:60px;
            margin:auto;
            background-color:white;
        }
    </style>
    <script>
        function writeInner(){
            document.getElementById('outerDiv').childNodes[1].innerHTML = 'Hi there';
        }
    </script>
<body>
    <div id="outerDiv">
        <div class="innerDiv">

        </div>

    </div>
    <button id="me" onClick="writeInner()">Click me!</button>

</body>
</html>
相关问题