Home > Software design >  javascript get elements inside other elements
javascript get elements inside other elements

Time:07-11

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:

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

CodePudding user response:

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) => {
  // ...
});
  • Related