javascripthtmlselection-api

using selectionStart on programmatically-created inputs


Is it possible to set and get .selectionStart and .selectionEnd on a <textarea> that I create programmatically?

Example

var input = document.createElement("textarea");
input.selectionStart; // 0 - just to confirm the property exists
input.selectionStart = 2; // returns 2
input.selectionStart; // returns 0, it should be 2

The above works fine in the textarea actually exists in the HTML of the page, but not when done as above (in Chrome at least).

The reason I want to do this is because I am testing a directive in AngularJS that manipulates a textarea and as part of my test I want to specify the position of the caret.

If not possible, is there a reason? And is there an alternative to setting the caret in a unit test?


Solution

  • Fiddle

    var input = document.createElement("textarea");
    
    // Add the manually created element to the document body
    document.body.appendChild(input);
    
    // Just added to confirm visually
    input.textContent = "Something clever here";
    input.selectionStart = 2; // returns 2
    input.selectionEnd = input.textLength - 2;