简体   繁体   English

javascript获取其他元素中的元素

[英]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.我正在尝试少用 jQuery,但我发现 dom 元素的选择或操作很难。 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.我不太清楚如何提出这个问题,但我正在尝试遍历来自 forEach 循环的元素内的元素。

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:在 jQuery 中,我会这样做:

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

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. querySelectorAll不仅可以在document上调用以查找文档的后代,还可以在节点上调用以查找与选择器匹配的该节点的后代。

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 .如果情况允许,您还可以组合选择器并仅使用单个querySelectorAll

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM