skip to Main Content
<div id="textarea">
abcd
<span id="cursor"></span>
</div>

How to delete character ‘d’ from the div tag using javascript or jquery ?

2

Answers


  1. You can remove the last char from the div using this mathod

    var $div = $("#textarea");
    var text = $div.text().trim();
    
    if (text.length > 0) {
      text = text.slice(0, -1); 
    }
    
    $div.html(text + '<span id="cursor"></span>');
    
    Login or Signup to reply.
  2. 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 the previousSibling property.

    In below snippet I have added text after the cursor, and styled the cursor as a red vertical bar:

    const node = document.querySelector("#cursor").previousSibling;
    node.textContent = node.textContent.replace(/S(s*)$/, "$1");
    #cursor { border-right: 2px solid red }
    <div>
      abcd
      <span id="cursor"></span>
      rest
    </div>

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search