JSFiddle - React, Tailwind, and code Playground
by tms
HTML
<div>
this is that is this is that is this is that
</div>
<div>
another bit of sample text for selecting text in text
</div>
<label>Position:</label><input id="position" type="text" size="15"><button id="update">Select</button>
<pre id="log">
</pre>
CSS
div { border:2px solid #404040; padding:8px; margin:8px; }
#log { margin:8px; }
label { margin-left: 8px; margin-right:6px; }
JavaScript
// Function to get selector path, sourced from
// http://stackoverflow.com/q/2068272/2068381#2068381
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.localName || realNode.tagName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
$('div').bind('mouseup', function () {
var position = getSelection();
if (position) {
$('#log').text($(position.node).getPath() + ' ' + position.offset +' ' + position.length);
} else {
$('#log').text('No position information');
}
});
$('#update').bind('click', function() {
var args = $('#position').val().split(' ');
if (args.length !== 3) {
$('#log').text('Invalid args');
}
setSelection({
'offset': parseInt(args[1]),
'length': parseInt(args[2]),
'node': $(args[0])[0]
});
$('#position').val('');
});
function getSelection() {
var selection, position;
if (window.getSelection) {
selection = window.getSelection();
if (selection && !selection.isCollapsed) {
position = {
'offset': selection.anchorOffset,
'length': selection.toString().length,
'node': selection.anchorNode.parentNode
};
}
} else if (document.selection) {
selection = document.selection.createRange();
if (selection && selection.text.length) {
var text = selection.parentElement().innerText,
range = document.body.createTextRange(),
...