0

Say I have a DOM model that has a collection of elements with class: class_1 and I use document.getElementsByClassName("class_1") to get an HTMLCollection of these elements.

If I take the first element of the collection is it possible to use the .getElementsByClassName("...") function again to get a secondary HTMLCollection of all the class_2 elements within the first element?

Connor
  • 867
  • 7
  • 18
  • 2
    Yes... https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByClassName – Peter Aug 24 '22 at 10:17
  • 1
    you mean getting children of the first `.class_1` element? it should be `let element = document.getElementsByClassName("class_1")[0]; let children = element.getElementsByClassName("class_2");` – GrafiCode Aug 24 '22 at 10:17
  • 2
    You'll find [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) easier to manage. It returns a non-live nodelist rather than a live HTML collection. – Andy Aug 24 '22 at 10:19
  • @Andy What's the difference between a live and non-live nodelist? – Connor Aug 24 '22 at 10:36
  • @Connor: https://stackoverflow.com/questions/14377590/queryselector-and-queryselectorall-vs-getelementsbyclassname-and-getelementbyid – Andy Aug 24 '22 at 10:40

2 Answers2

2

Yes, you can call getElementsByClassName on the document root, but you can also call it on any other element.

const classOne = document.getElementsByClassName("class1");
const classTwo = classOne[0].getElementsByClassName("class2");
Brandon
  • 385
  • 1
  • 8
2

You can, with querySelector/querySelectorAll : Like so:

let allDivs = document.querySelectorAll('div');
let justThat = allDivs.querySelector('.subItemClass'); // null if not found
flowtron
  • 854
  • 7
  • 20