Skip to content

Instantly share code, notes, and snippets.

@kingease
Last active October 10, 2018 11:47
Show Gist options
  • Select an option

  • Save kingease/0d51dc629c9151ff0738 to your computer and use it in GitHub Desktop.

Select an option

Save kingease/0d51dc629c9151ff0738 to your computer and use it in GitHub Desktop.
use jquery and createRange() to select some word in editable control
// require() some stuff from npm (like you were using browserify)
// and then hit Run Code to run it on the right
var $ = require('jquery');
var $main = $('#main');
$main.html('hello <s>world</s>');
$main.focus();
var nodes = $main.contents();
console.dir(nodes[1]);
var range = document.createRange();
range.setStart(nodes[0], 1);
range.setEnd(nodes[1].firstChild, 1);
var sel = document.getSelection();
sel.removeAllRanges();
sel.addRange(range);
// test selection
var sel = document.getSelection();
var selRange = sel.getRangeAt(0);
console.log(selRange.collapsed);
{
"name": "jquery select content in editor",
"version": "1.0.0",
"dependencies": {
"jquery": "2.1.4"
}
}
<!-- contents of this file will be placed inside the <body> -->
<h1>riddle editor</h1>
<div contentEditable="true" class="text-area" id="main"></div>
<!-- contents of this file will be placed inside the <head> -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment