title: DOM traversal with cheerio - How to get all the elements with their corresponding text
body: <p>So I'm using <strong>Cheerio</strong>, a library similar to jQuery on the <strong>Node server side</strong>, that allows you to parse an html text and traverse it just like you would with jQuery. I need to get the plain text of the html body, but not only that, I need to get the corresponding element and number. IE: if the plain text was found in the third paragraph element, I would have something like:</p>
  
  <pre><code>{
      text: &lt;element plaintext&gt;,
      element: "p-3"
  }
  </code></pre>
  
  <p>I currently have the following function that attempts to do this: </p>
  
  <pre><code>var plaintext_elements = traverse_tree($('body'));    
  
  function traverse_tree(root, found_elements = {}, return_array = []) {
      if (root.children().length) {
          //root has children, call traverse_tree on that subtree
          traverse_tree(root.children().first(), found_elements, return_array);
      }
      root.nextAll().each(function(i, elem) {
          if ($(elem).children().length) {
              //if the element has children call traverse_tree on the element's first child
              traverse_tree($(elem).children().first(), found_elements, return_array)
          }
          else {
              if (!found_elements[$(elem)[0].name]) {
                  found_elements[$(elem)[0].name] = 1;
              }
              else {
                  found_elements[$(elem)[0].name]++
              }
              if ($(elem).text() &amp;&amp; $(elem).text != '') {
                  return_array.push({
                      text: $(elem).text(),
                      element: $(elem)[0].name + '-' + found_elements[$(elem)[0].name]
                  })
              }
          }
      })
  
  
      if (root[0].name == 'body') {
          return return_array;
      }
  
  }
  </code></pre>
  
  <p>Am I going in the right direction, should I attempt something else? Any help on this would be appreciated. Again this is <strong>not jQuery</strong>, but Cheerio on the server side. (they are very similar, however)</p>