MattEnth
MattEnth

Reputation: 873

Get text from ElementRef?

Feels like this should be a pretty basic question...

I'm using a plugin that returns a DOM node / element that is NOT visible / rendered. I'm able to convert it easily to an ElementRef, with the nativeElement correctly populated.

How do I get the text of the element?

I know with AngularJS, I would do angular.elem(node).text()

Upvotes: 11

Views: 20061

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

To get the text content of the element, use the textContent or the innerText property:

elementRef.nativeElement.textContent
elementRef.nativeElement.innerText

An example is shown in this stackblitz.


Here are some of the differences between them, as given in the MDN documentation:

  • While textContent gets the content of all elements, including <script> and <style> elements, innerText does not.
  • innerText is aware of style and will not return the text of hidden elements, whereas textContent will.
  • As innerText is aware of CSS styling, it will trigger a reflow, whereas textContent will not.
  • Unlike textContent, altering innerText in Internet Explorer (up to version 11 inclusive) not only removes child nodes from the element, but also permanently destroys all descendant text nodes (so it is impossible to insert the nodes again into any other element or into the same element anymore).

Upvotes: 22

Related Questions