[英]why not my all div inside the div is getting the height of firstChild
我想让我的所有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
循环添加
您选择.r
并存储在第一个孩子var firstChild
,因此请使用如下,
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"; });
.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 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";
});
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.