Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Angular not grabbing elements by class name when page is loaded

I am trying to get the document.getElementsByClassName('side-nav-link-ref'); elements in my angular html view and It keeps returning empty. I’ve narrowed it down to the <ng-container> that I have doing a ngfor loop to display all the values in the array (Its creating a dropdown list). The loop is executing and displaying the page in the proper html tags and classes.

  <div #testElm>
    <ng-container *ngFor="let item of list">
       <p>This is a test 1</p>
       <p class="test-link">This is a test 2</p>
       <p>This is a test 3</p>
    </ng-container>
  </div>

When I run document.getElementsByClassName('side-nav-link-ref'); in the dev-tools console I get the desired results but when I run it in my project it shows me that It doesn’t see anything.

.ts file

@ViewChild('testElm') testElm!: ElementRef;

 list: any [] = [1];
 
  ngOnInit(): void {   
    this._testFunction(); 
  }
 
  _testFunction() { 
    const test: any = document.getElementsByClassName('test-link');
    for (let index = 0; index < test.length; index++) {      
      console.log('sTest: ' + test.length); 
      
    }
  }

The result should

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

ngOnInit is called when the component is loaded, but the view is still loading. You need ngAfterViewInit because you're trying to manipulate the dom/view. See Angular lifecycle hooks.

Also your ts file has the wrong classname.

about 4 years ago · Juan Pablo Isaza Report

0

Maybe you should use @ViewChildren and templateRef something like that example.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!