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:
What's the best way?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With