Home > Mobile >  How to use document.querySelector() to find elements with a specific class name that are within a di
How to use document.querySelector() to find elements with a specific class name that are within a di

Time:03-15

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 >Box A</div>
     <div >Box B</div>
 </div>

<div id="container2">
     <div >Box C</div>
     <div >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);
}

CodePudding user response:

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");

CodePudding user response:

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 >Box A</div>
     <div >Box B</div>
 </div>

<div id="container2">
     <div >Box C</div>
     <div >Box D</div>
</div>

  • Related