Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DOM elements by class, id, selectors and properties

Tags:

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?

like image 935
aaaaaaaaax10 Avatar asked Nov 23 '16 08:11

aaaaaaaaax10


People also ask

Which selects DOM element by ID?

In JavaScript, you can almost select any element from the DOM based on its unique ID by using the getElementById() method. It returns the first element that matches the given ID, or null if no matching element was found in the document.

How do you select an element with ID and class?

CSS ID will override CSS Class properties. To select an element with a specific id, write a hash (#) character, followed by the id of the element.


1 Answers

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

like image 51
Günter Zöchbauer Avatar answered Sep 18 '22 01:09

Günter Zöchbauer