6

I have a div and there is a text in it.I want a part of that text to be selected programmatically according position value of characters.

<div id="textdiv">
Hello world. I am a friend.
</div>

I want "llo world" part to be selected(I mean highlighted/selected like making selection of content in an input/textarea ). In that case position values are first (3) and last (10).

How can i do that programmatically using position values?

cinfis
  • 345
  • 4
  • 14

3 Answers3

11

Here is a simple way to to this:

function selectTextRange(obj, start, stop) {
  var endNode, startNode = endNode = obj.firstChild

  startNode.nodeValue = startNode.nodeValue.trim();
  
  var range = document.createRange();
  range.setStart(startNode, start);
  range.setEnd(endNode, stop + 1);
  
  var sel = window.getSelection();
  sel.removeAllRanges();
  sel.addRange(range);
}

selectTextRange(document.getElementById('textdiv'), 3, 10);
<div id="textdiv">
  Hello world. I am a friend.
</div>

Text highlight:

function highlightRange(el, start, end) {
  var text = el.textContent.trim()
  el.innerHTML = text.substring(0, start) + 
    '<span style="background:yellow">' +
    text.substring(start, end) + 
    "</span>" + text.substring(end);
}

highlightRange(document.getElementById("textdiv"), 3, 10)
<div id="textdiv">
  Hello world. I am a friend.
</div>
CoderPi
  • 12,985
  • 4
  • 34
  • 62
1

Code without any error checking ahead. Use at your own risk!

function highlight(pattern) {
  
  var text = $("#textdiv").text();
  var around = text.split(pattern);
  $("#textdiv").html(around[0] + "<span class='highlight'>" + pattern + "</span>" + around[1]);
  
}


$(document).ready(function() {

  highlight("world");
  
  
})
    
.highlight {
  
  background-color: yellow;
  
}
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<div id="textdiv">
  Hello world. I'm Hugo!
</div>
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
0

Try using .html() , String.prototype.slice(). To select "llo world" call .slice() with parameters 3, 12

$("#textdiv").html(function(i, html) {
  var selected = html.slice(3, 12);
  return html.replace(new RegExp("("+selected+")"), "<mark>$1</mark>")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="textdiv">
Hello world. I am a friend.
</div>
guest271314
  • 1
  • 15
  • 104
  • 177
  • i want selection as in textarea/input text selection – cinfis Jan 12 '16 at 15:59
  • 1
    @cinfis _"this is not what i want."_ , _" want selection as in textarea/input text selection"_ ? No `input` , `textarea` elements appear at Question ? – guest271314 Jan 12 '16 at 16:00