Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript get elements inside other elements

I’m trying to use less an less jQuery, but I find it hard for dom elements selection or manipulation.
I don’t know well how to ask this question, but I’m trying to loop over elements inside an element coming from a forEach loop.

this might be clearer with code:

const sections = document.querySelectorAll('.section')
sections.forEach(section => {
    // now get an array of boxes elements INSIDE this section (and only this one)
})

In jQuery I would do it this way:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$('.section').each((key, section) => {  
    $('.box', $(section)).each((key2, item) => {
        console.log($(item))
    })
})

>Solution :

querySelectorAll can be called not only on the document to find descendants of the document, but also on nodes to find descendants of that node that match the selector.

document.querySelectorAll('.section').forEach(section => {
  section.querySelectorAll('.box').forEach((box) => {
    // ...
  });
});

If the situation warrants, you can also combine the selectors and use only a single querySelectorAll.

document.querySelectorAll('.section .box').forEach((box) => {
  // ...
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading