JSFiddle - React, Tailwind, and code Playground
HTML
<select id='lineSelector'>
<option>- select line -</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select><br/>
<textarea id='tarea' cols='40' rows='5'>
first line
second line
third
fourth
fifth
</textarea>
JavaScript
function selectTextareaLine(tarea,lineNum) {
lineNum--; // array starts at 0
var lines = tarea.value.split("\n");
// calculate start/end
var startPos = 0, endPos = tarea.value.length;
for(var x = 0; x < lines.length; x++) {
if(x == lineNum) {
break;
}
startPos += (lines[x].length+1);
}
var endPos = lines[lineNum].length+startPos;
// do selection
// Chrome / Firefox
if(typeof(tarea.selectionStart) != "undefined") {
tarea.focus();
tarea.selectionStart = startPos;
tarea.selectionEnd = endPos;
return true;
}
// IE
if (document.selection && document.selection.createRange) {
tarea.focus();
tarea.select();
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
range.select();
return true;
}
return false;
}
/// debugging code
var sel = document.getElementById('lineSelector');
var tarea = document.getElementById('tarea');
sel.onchange = function() {
selectTextareaLine(tarea,this.value);
}