Angular2 retrieve all elements with class name

坚强是说给别人听的谎言 提交于 2019-11-30 17:14:20

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.

Answering as the comment worked for the OP.

You should be using

document.querySelectorAll('.classImLookingFor')

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);

you need to use DOM in angular

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

it works for me!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!