简体   繁体   English

如何使用 document.querySelector() 查找具有特定 ID 的 div 中具有特定名称 class 的元素

[英]How to use document.querySelector() to find elements with a specific class name that are within a div with a specific ID

In a CSS file, I can specify elements with a specific class name that are within a div with a specific ID like:在 CSS 文件中,我可以在具有特定 ID 的 div 中指定具有特定名称 class 的元素,例如:

<div id="container1">
     <div class="innerBox">Box A</div>
     <div class="innerBox">Box B</div>
 </div>

<div id="container2">
     <div class="innerBox">Box C</div>
     <div class="innerBox">Box D</div>
</div>
#container1 .innerBox {
     /* formatting */
}

So here, only boxes A and B would be formatted.所以在这里,只有盒子 A 和 B 会被格式化。

My question is- in a JS file, how can I use document.querySelector() to find elements with a specific class name that are within a div with a specific ID?我的问题是 - 在 JS 文件中,如何使用 document.querySelector() 查找具有特定 ID 的 div 中具有特定名称 class 的元素? Ex:前任:

var selectedItems = document.querySelector("#container1 .innerBox");

I confused on how the argument should be formatted我对参数的格式感到困惑

Additionally, since the inner class will vary, but the outer div will always be the same, I've tried to use the following code (unsuccessfully):此外,由于内部 class 会有所不同,但外部 div 将始终相同,因此我尝试使用以下代码(未成功):

function AddItem(boxClass) {
    var boxChosen = document.querySelector("#outer-panel ." + boxClass);
}

I think you need querySelectorAll to get all elements matching the condition, then use a for loop to do what you want.我认为您需要querySelectorAll来获取所有符合条件的元素,然后使用for循环来执行您想要的操作。

 function AddItem(boxClass) { // use `querySelectorAll` to get all elements. var boxChosen = document.querySelectorAll("#container2." + boxClass); return boxChosen } const elements = AddItem("innerBox") for (let i = 0; i < elements.length; i++) { // do something you want. elements[i].style.backgroundColor = 'blue' console.log(elements[i]) }
 <div id="container1"> <div class="innerBox">Box A</div> <div class="innerBox">Box B</div> </div> <div id="container2"> <div class="innerBox">Box C</div> <div class="innerBox">Box D</div> </div>

It works same as CSS selectors它与 CSS 选择器一样工作

If you want to select all elements with class .innerBox inside div #container1 use querySelectorAll()如果你想 select 所有元素与 class .innerBox inside div #container1使用querySelectorAll()

document.querySelectorAll("#container1 .innerBox");

if you want to select all the elements with the class .innerBox inside any div如果你想 select 任何 div 中带有 class .innerBox的所有元素

document.querySelectorAll("div .innerBox");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM