1

Why does this doesn't select (ie highlight in blue etc.) the contenteditable <div> ?

Note: I'm using Firefox 36.0.1 (Windows 7)

$('#b').click(function() { $('#a').select().focus(); } );
<div id="a" contenteditable>Hello</div>
<div id="b">click here</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Raibaz
  • 9,280
  • 10
  • 44
  • 65
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 1
    Seems to work for me. What browser are you using? – putvande May 10 '16 at 12:24
  • @putvande firefox 36.0.1 – Basj May 10 '16 at 12:25
  • 1
    Take a look at http://stackoverflow.com/questions/12243898/how-to-select-all-text-in-contenteditable-div – Nenad Vracar May 10 '16 at 12:33
  • @Basj -- Did you try to actually type something? contenteditable is html5 -- your browser may simply be too old to support it (I have FF 44 and works fine) – Soren May 10 '16 at 12:36
  • However [this](http://caniuse.com/#feat=contenteditable) suggest that it should work fine with your browser – Soren May 10 '16 at 12:38
  • @Soren no no, FF 36 supports contenteditable since a long time, I use it in many projects. The problem doesn't come from that. – Basj May 10 '16 at 12:39

2 Answers2

1

The select() function is not for a contenteditable Element. see@ https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select.

The HTMLInputElement.select() method selects all the text in a < textarea > element or an < input > element with a text field.

You can set a Range to select the text or a part of the text. To select the contenteditable text you can use this:

function selectAll() {
  var editor = document.getElementById('a');
  var selection = document.getSelection();
  selection.removeAllRanges();
  var range = document.createRange();
  range.selectNodeContents(editor);
  selection.addRange(range);
}

http://codepen.io/anon/pen/QNPGxW

0

As suggested here, this works, at least with Firefox:

$('#b').click(function() { $('#a').select().focus(); document.execCommand('selectAll', false, null); } );
<div id="a" contenteditable>Hello</div>
<div id="b">click here</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Community
  • 1
  • 1
Basj
  • 41,386
  • 99
  • 383
  • 673