get text of an element without children in javascript

This code achieves the same result as the two other answers, but in a more expressive, functional way. The filter and map array methods are supported in all modern browsers (IE9 and up).

Throwing this in there since the other answers are a bit dated by now.

var content = Array.prototype.filter.call(element.childNodes, function (element) {
    return element.nodeType === Node.TEXT_NODE;
}).map(function (element) {
    return element.textContent;
}).join("");

Just find the text nodes:

var element = document.getElementById('whatever'), text = '';
for (var i = 0; i < element.childNodes.length; ++i)
  if (element.childNodes[i].nodeType === Node.TEXT_NODE)
    text += element.childNodes[i].textContent;

edit — if you want the text in descendant ("children") nodes, and (as is now apparent) you're using jQuery:

$.fn.allText = function() {
  var text = '';
  this.each(function() {
    $(this).contents().each(function() {
      if (this.nodeType == Node.TEXT_NODE)
        text += this.textContent;
      else if (this.nodeType == Node.ELEMENT_NODE)
        text += $(this).allText();
    });
  });
  return text;
};

Hold on and I'll test that out :-) (seems to work)