54

Can anyone help with how to find 'All' Elements with a particular class name in Angular 2? I thought it would be trivial but it's giving me more problems that was prepared for.

<span class="classImLookingFor">foo</span>
<span class="classImLookingFor">Voo</span>
<span class="classImLookingFor">Moo</span>

I thought by doing what I have below would return all the elements with class "classImLookingFor" but it only returns the first instance.

constructor(private renderer: Renderer){}
ngAfterViewInit(){
 const el = this.renderer.selectRootElement('.classImLookingFor');
 this.renderer.setElementAttribute(el, 'tabindex', 0);
}

Afterwards, my markup looks like this.

<span class="classImLookingFor" tabindex="0">foo</span>
<span class="classImLookingFor">Voo</span>
<span class="classImLookingFor">Moo</span>

It seems like I should be able to create a Renderer array, but that doesn't seem to work either. I need to manipulate each element with that class name.

starball
  • 20,030
  • 7
  • 43
  • 238
dekaha1
  • 551
  • 1
  • 4
  • 4
  • 4
    you can use `document.querySelectorAll('.classImLookingFor')` – Aravind Apr 12 '17 at 17:37
  • Just what I was looking for. That works perfectly. For some reason though, document.getElementsByClassName didn't work for me,. Thanks for the speedy response. I was making it overly complicated – dekaha1 Apr 12 '17 at 18:43
  • can you upvote my answer as it helped you – Aravind Jul 02 '17 at 05:47

7 Answers7

88

Doesn't this return all the elements in the DOM? Is there a way how to return only elements generated by the Angular component I'm "in"?

You need to...

  1. Inject ElementRef in the constructor

    constructor(private renderer: Renderer, private elem: ElementRef){}
    
  2. Find the elements you are searching using querySelectorAll api.

    ngAfterViewInit(){
        // you'll get your through 'elements' below code
        let elements = this.elem.nativeElement.querySelectorAll('.classImLookingFor');
    }
    

The answer @Aravind has provided is not the best for the performance as it will search the whole DOM.

This solution will just search the DOM inside the current component.

Paritosh
  • 11,144
  • 5
  • 56
  • 74
17

Angular 10+ document compatibility with SSR, import:

import { DOCUMENT } from '@angular/common'

then inject:

constructor(@Inject(DOCUMENT) private _document: HTMLDocument) {
    }

And use in your component/ directive like this:

doSomething(): void {
 this._document.querySelectorAll('.classImLookingFor')
}
Nexeuz
  • 387
  • 2
  • 11
13

Answering as the comment worked for the OP.

You should be using

document.querySelectorAll('.classImLookingFor')
Aravind
  • 40,391
  • 16
  • 91
  • 110
  • 4
    Doesn't this return all the elements in the DOM? Is there a way how to return only elements generated by the Angular component I'm "in"? – Skorunka František Feb 03 '18 at 14:00
  • @SkorunkaFrantišek, u're right, check [this answer](https://stackoverflow.com/questions/43376081/angular2-retrieve-all-elements-with-class-name/#48928778) – Paritosh Feb 26 '18 at 08:48
  • I upvoted because this is useful if you want to reference an element in the document which is outside the Angular component you are "in". – Yvonne Aburrow Jul 17 '19 at 19:12
5

This might be a little over-simplistic for your use case, but is there any reason you can't use the native DOM functions, like so?

var domRepresentation = document.getElementsByClassName('classImLookingFor');
var angularElement = angular.element(domRepresentation);
Billy Barry
  • 187
  • 6
2

There are various ways to do but the latest provided by Angular 9+ versions are:

1.import Inject and DOCUMENT in angular.

import {Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

2.Then create a reference in the constructor of the required class.

constructor(@Inject(DOCUMENT) private _document: HTMLDocument) {}

3.Use as a variable with all javascript methods available.

selectElement(): void {
 this._document.querySelector('#mySelectedId');
}
Amit Singh
  • 279
  • 2
  • 7
0

Use case; Press escape key -> Remove border of marked row

enter image description here

  resetMarkedRows():void{
    const rowContainer = document.getElementById('row-container');
    //get row node list
    const rowNodes = rowContainer && rowContainer.querySelectorAll('.row-outer');
    //convert node list to an array
    const rows = Array.from(rowNodes) as HTMLElement[];
    const markedRows = rows.filter((row:HTMLElement)=>{
      if(row.style.border == "1px solid rgb(0, 136, 255)"){
        return row
      }
    });
    markedRows[0].style.border = "none";
  }
Lojith Vinsuka
  • 906
  • 1
  • 10
  • 8
-4

you need to use DOM in angular

var element=document.getElementsByClassName("X").item(0);

it works for me!