0

I am attempting to programatically add multiple selection regions in Chrome.

From here: Can you set and/or change the user’s text selection in JavaScript?

I found this function for selecting an elements text on SO (I added the clearFirst parameter):

function selectElementContents(el, clearFirst) {
    if (window.getSelection && document.createRange) {
//        console.log('here');
        var sel = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(el);
        if (clearFirst) sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.selection && document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
    }
}

and then tried calling it like this:

  var table = document.createElement("table");
  document.body.appendChild(table);
  for (var i = 0; i < 3; i++) {
    let row = table.insertRow();
    for (var j = 0; j < 3; j++) {
       let cell = row.insertCell();
       cell.innerText = "" + i + "," + j;
    }
  }
  $(table).on("click", function() {
    let tds = $(this).find("td");
    console.log("td: " + tds.get(0));
    selectElementContents(tds.get(0), true);
    selectElementContents(tds.get(3), false);

  });

The selection of the first TD works fine, but the second range is not selected. I confirmed that selectElementContents is going through the "true" code (where the commented out console.log is). Is adding multiple selection ranges in Chrome disallowed, or am I just not doing this correctly?

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80

1 Answers1

0

The answer appears to be contained in a Chrome extension: "Multiline Text Selection" https://chrome.google.com/webstore/detail/multiline-text-selection/ajbomhojbckleofgngogoecoaefclnol?hl=en

So in default chrome, multiple selection ranges isn't supported. But this extension can enable it.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80