title: Using jQuery to gather all text nodes from a wrapped set, separated by spaces
body: <p>I'm looking for a way to gather all of the text in a jQuery wrapped set, but I need to create spaces between sibling nodes that have no text nodes between them.</p>
  
  <p>For example, consider this HTML:</p>
  
  <pre><code>&lt;div&gt;
    &lt;ul&gt;
      &lt;li&gt;List item #1.&lt;/li&gt;&lt;li&gt;List item #2.&lt;/li&gt;&lt;li&gt;List item #3.&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>If I simply use jQuery's <code>text()</code> method to gather the text content of the <code>&lt;div&gt;</code>, like such:</p>
  
  <pre><code>var $div = $('div'), text = $div.text().trim();
  
  alert(text);
  </code></pre>
  
  <p>that produces the following text:</p>
  
  <blockquote>
    <p>List item #1.List item #2.List item #3.</p>
  </blockquote>
  
  <p>because there is no whitespace between each <code>&lt;li&gt;</code> element. What I'm actually looking for is this (note the single space between each sentence):</p>
  
  <blockquote>
    <p>List item #1. List item #3. List item #3.</p>
  </blockquote>
  
  <p>This suggest to me that I need to traverse the DOM nodes in the wrapped set, appending the text for each to a string, followed by a space. I tried the following code:</p>
  
  <pre><code>var $div = $('div'), text = '';
  
  $div.find('*').each(function() {
    text += $(this).text().trim() + ' ';
  });
  
  alert(text);
  </code></pre>
  
  <p>but this produced the following text:</p>
  
  <blockquote>
    <p>This is list item #1.This is list item #2.This is list item #3. This is list item #1. This is list item #2. This is list item #3. </p>
  </blockquote>
  
  <p>I assume this is because I'm iterating through every descendant of <code>&lt;div&gt;</code> and appending the text, so I'm getting the text nodes within both <code>&lt;ul&gt;</code> and each of its <code>&lt;li&gt;</code> children, leading to duplicated text.</p>
  
  <p>I think I could probably find/write a plain JavaScript function to recursively walk the DOM of the wrapped set, gathering and appending text nodes - but is there a simpler way to do this using jQuery? Cross-browser consistency is very important.</p>
  
  <p>Thanks for any help!</p>