-2

Say my component is simple, like:

<div>
  <button id="one" #one>one</button>
  <button id="two" #two>two</button>
  <button id="three" #three>three</button>
</div>

Would it be possible to return a list of all of the buttons?

ie.

constructor() {
  let buttonList = findByElement('button');
}
physicsboy
  • 5,656
  • 17
  • 70
  • 119

2 Answers2

1

Use document.querySelectorAll()

var div=document.getElementById("div");
var a=div.querySelectorAll('button');
console.log(Object.values(a))
<div id="div">
  <button id="one" #one>one</button>
  <button id="two" #two>two</button>
  <button id="three" #three>three</button>
</div>
ellipsis
  • 12,049
  • 2
  • 17
  • 33
0

If you add Renderer and ElementRef to your component, you should then be able to access the element in question:

constructor(private renderer: Renderer, private elem: ElementRef){}

I believe from within your component you can call:

const elements = this.elem.nativeElement.querySelectorAll('button');

Which would give you the elements you need. It's important when using this method to ensure that you're running your code at some point after the component is initialised, not in the constructor as was the case with your original code, as we need to ensure we have access to the DOM for this component. This question has more detail.

OliverRadini
  • 6,238
  • 1
  • 21
  • 46