如何仅通过查询选择器选择 r
中的 div p
和 p2
,我不想选择 div p
和 p2
如果它不在类 r
<div>
<div class="r"><div class="p"></div><div class="p2"></div></div> //want to select this , i know it can accessed with tad name div
</div>
<div class="r"><div class="p"></div><div class="p2"></div></div> // I dont want to select this if the parent div is body
CSS
.p,.p2{
height:50px;
width:50px;
background-color:orange
}
我试过的 javascript 是,这是正确的实现方式吗
c = document.querySelectorAll( ' x >.r' ) // where x is the parent tag tagName of r
最佳答案
所以根据您的要求,您只想选择第一个 child 的后代,
然后只需使用 :first-child
选择器。
var firstChild = document.querySelector(".r:first-child");
var descendant = firstChild.querySelectorAll(".p, .p2");
Array.from(descendant).forEach(function(itm){
itm.style.backgroundColor = "red";
});
DEMO
关于javascript - 按 div 内的类名选择所有 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41311360/