26

How can I get DOM elements by class, id, selectors (div > .my-i) and properties like in jQuery?

For example:

<div class="myClass" style="width:200px">
<span id="pop">test</span>
<div>
  <i>aaa</i>
  <i class="my-i">bbb</i>
  <i class="my-i">ccc</i>
</div>

I need to get:

  1. value 200px by class
  2. text 'test' by id
  3. all by class="my-i"

What's the best way?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
aaaaaaaaax10
  • 599
  • 2
  • 9
  • 21

1 Answers1

53
constructor(private elRef:ElementRef) {}

ngAfterViewInit() {
  this.elRef.nativeElement.querySelector('.myClass');
}

This will not work well with Web Workers or Universal, but Angular2 itself doesn't provide something platform-agnostic to query for elements.

See also angular 2 / typescript : get hold of an element in the template

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 4
    `@ViewChild()` doesn't support CSS selectors, only template variable names or directive/component types. – Günter Zöchbauer Nov 23 '16 at 08:58
  • 1
    Anyone know how to get a DOM element via CSS Selector as the OP asked? As mentioned above, `@ViewChild` and `element.nativeElement` will not work for this scenario. – atconway Sep 19 '17 at 17:02
  • 1
    @atconway What's the problem. My code shows how to use CSS selectors. What do you mean by "this scenario"? Angular itself doesn't provide anything. If you want to use CSS selectors, you have to use ´nativeElement` or `window`. – Günter Zöchbauer Sep 19 '17 at 17:04
  • `(renderElement as any)[methodName].apply(renderElement, args);` https://angular.io/guide/migration-renderer – rofrol Jun 10 '22 at 11:49