javascript - 按 div 内的类名选择所有 div

标签 javascript

如何仅通过查询选择器选择 r 中的 div pp2,我不想选择 div pp2 如果它不在类 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/

相关文章:

javascript - 如何使用扩展程序在 Google Chrome 中加载页面?

javascript - 如何使用 jQuery 在两个数组中选择相同的对象?

javascript - 如何设置上一个日期在 UI datepicker 中变为非事件状态

扩展中的javascript不起作用

javascript - Vue 可以计算或观察 body 的 scrollHeight 吗?

javascript - 事件 | jQuery 还是 Backbone?

JavaScript TypedArray 混合类型

javascript - Web 动画 API - 如何在关键帧脚本中使用变量?

javascript - AngularJS 摘要循环究竟是如何工作的?

javascript - 页面加载原型(prototype)后如何选择选项?