1

In a CSS file, I can specify elements with a specific class name that are within a div with a specific ID like:

<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.

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? 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):

function AddItem(boxClass) {
    var boxChosen = document.querySelector("#outer-panel ." + boxClass);
}
user18467332
  • 19
  • 1
  • 1
  • 2
  • 1
    The first line you have is exactly how it works. The syntax is the same as the selector in your CSS files. The second version will also work. However you probably want `.querySelectorAll` instead to actually get a list of matches as opposed to just the first match. If you have issues, please create a [mre]. –  Mar 14 '22 at 23:49
  • 1
    You can check [link](https://stackoverflow.com/questions/12166753/how-to-get-child-element-by-class-name) this – Mehmet YILMAZ Mar 14 '22 at 23:51

2 Answers2

0

I think you need querySelectorAll to get all elements matching the condition, then use a for loop to do what you want.

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>
Jay Lu
  • 1,515
  • 8
  • 18
0

It works same as CSS selectors

If you want to select all elements with class .innerBox inside div #container1 use querySelectorAll()

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

if you want to select all the elements with the class .innerBox inside any div

document.querySelectorAll("div .innerBox");
pallavdubey
  • 109
  • 6