How to get all element by class in Angular?

Issue

I have tried this way:

let elements = this.elRef.nativeElement.querySelector('.class-block-list-item');

elements.forEach((element) => {
  console.log(element);
});

It returns me only one HTML element, not array

Solution

The querySelector function only retrieves the first ocurrence of the selection. If you want to get all of them you need to use querySelectorAll as shown below:

let elements = this.elRef.nativeElement.querySelectorAll(".class-block-list-item");

Answered By – GmoRubio

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.