Home > Blockchain >  Can you search a HTMLElement for a particular class?
Can you search a HTMLElement for a particular class?

Time:08-25

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?

CodePudding user response:

You can, with querySelector/querySelectorAll : Like so:

let allDivs = document.querySelectorAll('div');
let justThat = allDivs.querySelector('.subItemClass'); // null if not found

CodePudding user response:

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");
  • Related