-1

after a bit of help, I'm relatively new to Javascript, I've got the contents of a div tag that I want to select when the user clicks a button, but I can't get it to work. It seems relativity simple, but I've been playing around for hours and can't find a solution

<div id="targetText">content content </div>

<button type="button" onclick="selectBox()">Push to Select</button>

With the following Javascript

function selectBox() {
document.getElementById("targetText").select();
}

But nothing happens when I click the button!

It works fine when I ask it to select an input (as below), but the content I want selected is in a div

<input type="text" id="targetText" value="content content">

Any suggestions? Thanks in advance

WillMaddicott
  • 512
  • 6
  • 20
  • I recommend the second answer in the duplicate - `window.getSelection().selectAllChildren( document.getElementById('targetText'));` – Dominic Apr 25 '18 at 10:39

1 Answers1

1
<button type="button" onclick="selectBox(document.getElementById('targetText'))">Push to Select</button>

function selectBox(elem) {

//Create a range (a range is a like the selection but invisible)
var range = document.createRange();

// Select the entire contents of the element
range.selectNodeContents(elem);

// Don't select, just positioning caret:
// In front
// range.collapse();
// Behind:
// range.collapse(false);

// Get the selection object
var selection = window.getSelection();

// Remove any current selections
selection.removeAllRanges();

// Make the range you have just created the visible selection
selection.addRange(range);

}

Roopak Puthenveettil
  • 1,387
  • 2
  • 13
  • 27