Example Adding SubScript

by karlovac

HTML

<input type="text" id="textInput" value="HO"/>

<button onClick="addTwo()">
    ₂
</button>

<p>
    Put your cursor between the H and the O and click the ₂ button.
</p>

CSS

input, button {
    font-size: 36px;
}

JavaScript

function addTwo() {
  	var element = document.getElementById('textInput');
    var newString = element.value.slice(0, element.selectionStart) + '₂' + element.value.slice(element.selectionStart, element.value.length);
    element.value = newString;
}