0

How can I select all text in an element?

<div class="wrapper">
    <div class="content">Lorem ipsum dolor sit amet.</div>
</div>

"Wrapper" is an ElementRef. How can I select all text (like Hightlight text) in '.content'?

I tried the following but did not succeed:

const selectedElm = selectedRef.nativeElement
(selectedElm.querySelector('.content') as HTMLInputElement).select();
(selectedElm.querySelector('.widget-content') as HTMLInputElement).setSelectionRange(0, 5)
bui quang huy
  • 153
  • 1
  • 2
  • 12

1 Answers1

1

You can't select (character by character) text of normal element text in a document. (Not even with JQuery's .select(). You need to have the text be in some sort of editable container for that to work.

You can accomplish this with a createRange()

var x = document.querySelector(".wrapper");

// Depending on which method is supported by browser
if (document.selection) {
  // Create a range of text object
  var range = document.body.createTextRange();
  range.moveToElementText(x); // Apply range to element in question
  range.select();  // Now, select will work
} else if (window.getSelection) {
  var range = document.createRange();
  range.selectNode(x);
  window.getSelection().removeAllRanges();
  window.getSelection().addRange(range);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div class="content">Lorem ipsum dolor sit amet.</div>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71