为什么我div中的所有div都没有达到firstChild的高度

时间:2016-12-24 11:45:55

标签: javascript html css

我想让我的所有div高度等于内部div的第一个子节点 这里我有三个div p , p2 , p3,它位于另一个名为(class)r的div中,我希望p2 , p3相同的高度为p

HTML

<div>
  <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
</div>

CSS

.p,.p2,.p3{
  display:inline-block;
  width:80px;
}
.p{
  height:50px;
}

JS

var firstChild = document.querySelector(".r:first-child");
var descendant = firstChild.querySelectorAll(".p, .p2,.p3");

[].forEach.call(descendant, function(itm){ 
  itm.style.backgroundColor = "green";
  var ch = document.getElementsByClassName("p").clientHeight;
  for(var i = 0 ;i < ch.length; i++ ){
  itm.style.height = ch[i] + "px";
  }
});

演示 - https://jsfiddle.net/104sn7mu/13/

修改1

循环添加

3 个答案:

答案 0 :(得分:2)

您已选择.r并将第一个孩子存储在var firstChild中,因此请按以下方式使用,

&#13;
&#13;
var firstChild = document.querySelector(".r:first-child");
var descendant = firstChild.querySelectorAll(".p, .p2,.p3");

[].forEach.call(descendant, function(itm){ 
  itm.style.backgroundColor = "green";
  var ch = firstChild.clientHeight;
  itm.style.height = ch + "px";
});
&#13;
.p,.p2,.p3{
  display:inline-block;
  width:80px;
}
.p{
  height:50px;
}
&#13;
<div>
  <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以使用你之前制作的变量:

var firstChild = document.querySelector(".r:first-child");
var descendant = firstChild.querySelectorAll(".p, .p2,.p3");

[].forEach.call(descendant, function(itm){ 
  itm.style.backgroundColor = "blue";
  var ch = firstChild.clientHeight;
  itm.style.height = ch + "px";
});

答案 2 :(得分:0)

var r = document.querySelectorAll(".r");
r.forEach(function(pel){
var rChildren = pel.querySelectorAll(".p, .p2,.p3");
rChildren.forEach(function(el){ 
  el.style.backgroundColor = "green";
  var ch = rChildren[0].clientHeight; // 1st child clientHeight of all elements under div having class r
  el.style.height = ch + "px";
});
});
.p,.p2,.p3{
  display:inline-block;
  width:80px;
}
.p{
  height:50px;
}
<div>
  <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
</div>

var r = document.querySelectorAll(".r");
r.forEach(function(pel){
var rChildren = pel.querySelectorAll(".p, .p2,.p3");
rChildren.forEach(function(el){ 
  el.style.backgroundColor = "green";
  var ch = rChildren[0].clientHeight; // 1st child clientHeight of all elements under div having class r
  el.style.height = ch + "px";
});
});
.p,.p2,.p3{
  display:inline-block;
  width:80px;
}
.p{
  height:50px;
}
<div>
  <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
  <br><br>
    <div class="r">
    <div class="p">fgdsgs</div>
    <div class="p2">sdgdfg</div>
    <div class="p3">sdgdfg</div>
  </div>
</div>