javascripthtmltextareaselectionselection-api

adding html tags to selected text in textarea. Why does "if('selectionStart' in textarea)" need to be in there?


I found javascript code that allows me to add html tags around text that I have highlighted in the textarea field:

    <textarea id="myArea" cols="30" spellcheck="false">Select some text within this field.</textarea>
        <button onclick="ModifySelection ()">Modify the current selection</button>

<script>
      function ModifySelection () {
                var textarea = document.getElementById("myArea");
          if('selectionStart' in textarea){
          if (textarea.selectionStart != textarea.selectionEnd) {
                        var newText = textarea.value.substring (0, textarea.selectionStart) + 
                            "[start]" + textarea.value.substring  (textarea.selectionStart, textarea.selectionEnd) + "[end]" +
                            textarea.value.substring (textarea.selectionEnd);
                        textarea.value = newText;
                    }
                }
    }
</script>

My questions pertain to this line, if('selectionStart' in textarea){:

  1. What does the line mean exactly?
  2. Why does selectionStart have to be in quotes?
  3. selectionStart is usually appended to an object like "textarea"(textarea.selectionStart), how is it possible to refer to it by itself?
  4. Is If(X in Y){} standard javascript syntax or does it work specifically forselectionStart?

note: I'm testing this in jsfiddle


Solution

    1. if('selectionStart' in textarea) is feature testing - it checks whether the textarea object has a selectionStart property.

    2. It needs to be in quotes as otherwise it would be interpreted as a variable (which may or may not exist in the current context).

    3. It depends on the browser and what version of HTML is supported and rendered.

    4. Yes it is normal javascript syntax. It is used to test if the specified property is in the object. See in on MDN.