最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Get all child elements by className or querySelectorAll with Javascript - Stack Overflow

programmeradmin1浏览0评论

I searched a lot for an answer, but I didn't find any proper solution.

I'd like to get all HTML elements that are inside of all divs with the same className, but it is important all of them be part of the same collection, or array or anything that allow me to loop through it.

Let's say that I have two divs with a class called 'divTest', if I use querySelectorAll to reach it I will get a childList with two indexes, 0 for the first div and 1 for the second. It would give me all elements inside these divs, but they wouldn't be together. I'd like to access both indexes at once.

I am accessing each element by its index and putting it inside an array, where I spread both:

submits = document.querySelectorAll(".divTest")[0].children;
submits1 = document.querySelectorAll(".divTest")[1].children;
arrayTeste = [...submits, ...submits1]

It works, but I'd like to know if there is a direct way to do this, like accessing both indexes on the same code line?

I searched a lot for an answer, but I didn't find any proper solution.

I'd like to get all HTML elements that are inside of all divs with the same className, but it is important all of them be part of the same collection, or array or anything that allow me to loop through it.

Let's say that I have two divs with a class called 'divTest', if I use querySelectorAll to reach it I will get a childList with two indexes, 0 for the first div and 1 for the second. It would give me all elements inside these divs, but they wouldn't be together. I'd like to access both indexes at once.

I am accessing each element by its index and putting it inside an array, where I spread both:

submits = document.querySelectorAll(".divTest")[0].children;
submits1 = document.querySelectorAll(".divTest")[1].children;
arrayTeste = [...submits, ...submits1]

It works, but I'd like to know if there is a direct way to do this, like accessing both indexes on the same code line?

Share Improve this question edited Nov 14, 2019 at 0:38 Berg_Durden asked Nov 14, 2019 at 0:32 Berg_DurdenBerg_Durden 1,7796 gold badges33 silver badges63 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

Use .divTest > * to select all elements which are immediate children of an element with a divTest class:

console.log(
  document.querySelectorAll('.foo > *').length
);
<div class="foo">
  <div></div>
  <div></div>
</div>
<div class="foo">
  <div></div>
  <div></div>
</div>

发布评论

评论列表(0)

  1. 暂无评论