Henrik Petterson Henrik Petterson - 6 months ago 15
jQuery Question

Select part of text after it's been added

I have this code:

$sel = 'lorem ipsum';
jQuery(this).html('<p>Hello world ' + $sel +' great day!');


So the
.html()
is added via ajax.

I want the
$sel
text to be selected when it's output on the page (as if the user highlighted it with their cursor).

I have the following code to select elements:

function SelectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}


How can I use that code and select just the text within
$sel
? So, output the html and select the
$sel
part.

Answer

The function below (createSelectedSpan) accepts a single argument, value. Every time this function is called, a new local variable sel, with the value of span element, is created. The sel's innerHTML is set to the value of argument value. Then, sel is adopted as a child by body. And at last sel is selected.

Besides this, I've modified your SelectText function to set the variable text defined inside it to the DOM Node passed to it as an argument.

This function can be called multiple times without any error with the newly added element being selected and other elements being deselected.

  function SelectText(element) {
  var doc = document,
    text = element,  // A modification is made here
    range, selection;
  if (doc.body.createTextRange) {
    range = document.body.createTextRange();
    range.moveToElementText(text);
    range.select();
  } else if (window.getSelection) {
    selection = window.getSelection();
    range = document.createRange();
    range.selectNodeContents(text);
    selection.removeAllRanges();
    selection.addRange(range);
  }
}

function createSelectedSpan(value){
  var sel = document.createElement("span");
  sel.innerHTML = value;

  $("body").append(sel);

  
  SelectText(sel);
}

createSelectedSpan("hello world");
setTimeout(function(){createSelectedSpan("hello world2")},5000); //called second time
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>