<div id="textarea">
abcd
<span id="cursor"></span>
</div>
How to delete character ‘d’ from the div tag using javascript or jquery ?
<div id="textarea">
abcd
<span id="cursor"></span>
</div>
How to delete character ‘d’ from the div tag using javascript or jquery ?
2
Answers
You can remove the last char from the div using this mathod
With plain JavaScript this may be easier, as jQuery is not very powerful on working with text nodes.
You can get the targeted text node by first selecting the
<span>
element, and then taking thepreviousSibling
property.In below snippet I have added text after the cursor, and styled the cursor as a red vertical bar:
Note that this does not touch the
<span>
itself, or any other sibling elements, nor does this solution make assumptions about the presence of other siblings. It only expects that the<span>
element is preceded by a text node that needs to lose its last non-white space character.Secondly, it doesn’t remove the trailing white-space characters (if any). If removed, it might render the
<span>
closer to the text than intended. To keep that white-space untouched, a regular expression is used to identify the last non-white space character, and it only removes that one character.