通过第二个子ID获取元素

时间:2016-08-24 09:21:04

标签: element

我想更改第二个ID" myDIV"第二个p标签(索引4)类"孩子" backgropund颜色。但我的脚本不起作用。如何获得第二个孩子ID?

<div id="myDIV">
  <p class="child">First p element with class="child" in a div (index 0).</p>
  <p class="child">Second p element with class="child" in a div (index 1).</p>
  <p class="child">Third p element with class="child" in a div (index 2).</p>
</div>

<div id="myDIV">
  <p class="child">First p element with class="child" in a div (index 3).</p>
  <p class="child">Second p element with class="child" in a div (index 4).</p>
  <p class="child">Third p element with class="child" in a div (index 5).</p>
</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.getElementById("myDIV")[1];
    x.getElementsByClassName("child")[2].style.backgroundColor = "red";
}
</script>

1 个答案:

答案 0 :(得分:0)

元素ID在整个文档中应该是唯一的。

你可以替换id =&#34; myDIV&#34; with class =&#34; myDiv&#34;

然后将脚本更改为

<script>
function myFunction() {
var x = document.getElementsByClassName("myDIV")[1];
x.getElementsByClassName("child")[1].style.backgroundColor = "red";
}
</script>

&#13;
&#13;
<div class="myDIV">
  <p class="child">First p element with class="child" in a div (index 0).</p>
  <p class="child">Second p element with class="child" in a div (index 1).</p>
  <p class="child">Third p element with class="child" in a div (index 2).</p>
</div>

<div class="myDIV">
  <p class="child">First p element with class="child" in a div (index 3).</p>
  <p class="child">Second p element with class="child" in a div (index 4).</p>
  <p class="child">Third p element with class="child" in a div (index 5).</p>
</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.getElementsByClassName("myDIV")[1];
    x.getElementsByClassName("child")[1].style.backgroundColor = "red";
}
</script>
&#13;
&#13;
&#13;