-2

Say I have the following HTML:

<div>Some text</div>

I'm wanting to remove the last character from the text each time the user hits the backspace key. Is there a way to actually remove a character from a text node? Or do I have to do something like obj.innerText = 'Some tex' (i.e. trim the last char myself and replace the whole thing).

Kong
  • 8,792
  • 15
  • 68
  • 98
  • You should look into a few frameworks/libraries that have these kind of view-model bindings baked in. http://angularjs.org/ or http://knockoutjs.com/ to name a few. – Ken Jul 29 '13 at 02:45
  • 1
    Have you tried [`contenteditable`](https://developer.mozilla.org/en-US/docs/Web/HTML/Content_Editable)? – Jonathan Lonowski Jul 29 '13 at 02:55

3 Answers3

1
var div = document.getElementById('my-div');
document.addEventListener('keydown', 
    function(e) {
        if (e.which === 8) {
            div.textContent = div.textContent.substring(0, div.textContent.length - 1);
        }
    }, false);

You may also want to support IE8. In that case, use document.attachEvent() and div.innerText.

Jackson
  • 9,188
  • 6
  • 52
  • 77
0

Best method I can think of off the top of my head is to use the substring method for Strings.

var s = obj.innerText

// Then On backspace event listener
s = s.substring(0, s.length - 1) // returns s without the last character in the original string.

obj.innerTezt(s) // set the inner HTML back to s

Edit: thanks Jonathan, Dennis for the correction on this answer!

  • 3
    You have the basic idea, but a few issues: 1) [`textContent`](https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent) is the standardized property and will need to be mixed with `innerText` for legacy support. 2) `s` isn't a *pointer* to `obj.innerText`; it's a copy. Setting it won't affect `obj.innerText` (or `obj.textContent`). – Jonathan Lonowski Jul 29 '13 at 03:01
  • Nice catch! You're right Jonathan - I missed the last bit that he'd have to set innerText/innerHTML again after getting the substring! –  Jul 29 '13 at 03:08
  • 1
    `innerHTML` is not a function – Dennis Jul 29 '13 at 03:11
0
// Get the element
var el = document.queryString("...")

// Get the text contents
var text = el.firstChild
if (text.nodeType === Node.TEXT_NODE) {
   // Delete the last character
   text.deleteData(text.length - 1, 1)
}

See the CharacterData DOM interface for details of deleteData