4

I have an piece of html in a jquery object. When I say $(this).html() I get:

<span class="value">4</span><span class="type">teaspoons</span>butter

I want to get only the piece of text from this html segment that is not in the spans. in this example, it is butter.

How do I get that?

Thanks!

Barka
  • 8,764
  • 15
  • 64
  • 91
  • 1
    Possible duplicate of http://stackoverflow.com/questions/1476787/jquery-innertext-not-including-sub-element – Roman Apr 13 '10 at 03:53
  • Also essentially the same question: http://stackoverflow.com/questions/2775893/how-to-get-the-text-of-a-div-which-is-not-a-part-of-any-other-container-in-jquery/3003950#3003950 – gnarf Jun 09 '10 at 07:54

3 Answers3

1

There's the easy but cheating way, drop all the children and get the text property

var tmp = $(".post-text").clone();
tmp.children().remove();
tmp.text();

EDIT There is also a Text Children plugin that does this.

Roman
  • 19,581
  • 6
  • 68
  • 84
0
var textvalues = $(this).contents().map(function() {
  return this.nodeType === 3 ? this.nodeValue : null;
});
wombleton
  • 8,336
  • 1
  • 28
  • 30
0

This example uses .contents() to get all the children nodes (including text nodes), then uses .map() to turn each child node into a string based on the nodeType. If the node is a text node (i.e. text not within the spans), we return its nodeValue.

This returns a jQuery set containing strings, so we call .get() to get a 'standard' array object that we can call .join() on.

// our 'div' that contains your code:
var $html = $('<div><span class="value">4</span><span class="type">teaspoons</span>butter</div>');

// Map the contents() into strings
$html.contents().map(function() { 
  // if the node is a textNode, use its nodeValue, otherwise empty string
  return this.nodeType == 3 ? this.nodeValue : ''; 
  // get the array, and join it together:
}).get().join('');

// "butter"

If you need to do this a lot, you could make a quick plugin:

$.fn.directText = function() {
   return this.contents().map(function() {
     return this.nodeType == 3 ? this.nodeValue : '';
   }).get().join('');
};

Or a slightly more robust version that supports stripping whitespace / changing the text that it joins the resulting array with:

$.fn.directText = function(settings) {
   settings = $.extend({},$.fn.directText.defaults, settings);
   return this.contents().map(function() {
     if (this.nodeType != 3) return undefined; // remove non-text nodes
     var value = this.nodeValue;
     if (settings.trim) value = $.trim(value);
     if (!value.length) return undefined; // remove zero-length text nodes
     return value;
   }).get().join(settings.joinText);
};

$.fn.directText.defaults = {
   trim: true,
   joinText: ''
};
gnarf
  • 105,192
  • 25
  • 127
  • 161