Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
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:

<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);
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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>

about 4 years ago · Juan Pablo Isaza Report

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");
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!