title: Get text of previous header in HTML
body: <p>I have a HTML which looks like this:</p>
  <pre><code>&lt;h1&gt;Title&lt;/h1&gt;
  &lt;p&gt;Some additional content, can be multiple, various tags&lt;/p&gt;
  &lt;h2&gt;&lt;a id=&quot;123&quot;&gt;&lt;/a&gt;Foo&lt;/h2&gt;
  &lt;p&gt;Some additional content, can be multiple, various tags&lt;/p&gt;
  &lt;h3&gt;&lt;a id=&quot;456&quot;&gt;&lt;/a&gt;Bar&lt;/h3&gt;
  </code></pre>
  <p>Now, for each anchor with id, I want to find out the header hierarchy, e.g. for the anchor with <code>id=&quot;123&quot;</code> I would like to get something like <code>[{level: 1, title: &quot;Title&quot;}, {level: 2, title: &quot;Foo&quot;}]</code>, similarly for anchor with <code>id=&quot;456&quot;</code>, I would like to get <code>[{level: 1, title: &quot;Title&quot;}, {level: 2, title: &quot;Foo&quot;}, {level: 3, title: &quot;Bar&quot;}]</code>.</p>
  <p>My code looks like this so far:</p>
  <pre class="lang-js prettyprint-override"><code>const linkModel: IDictionary&lt;ILinkModelEntry&gt; = {};
  const $ = cheerio.load(html);
  $(&quot;a&quot;).each((_i, elt) =&gt; {
      const anchor = $(elt);
      const id = anchor.attr().id;
      if (id) {
          const parent = anchor.parent();
          const parentTag = parent.prop(&quot;tagName&quot;);
          let headerHierarchy: any[] = [];
          if ([&quot;H1&quot;, &quot;H2&quot;, &quot;H3&quot;, &quot;H4&quot;, &quot;H5&quot;, &quot;H6&quot;].includes(parentTag)) {
              let level = parseInt(parentTag[1]);
              headerHierarchy = [{level, text: parent.text()}];
              level--;
              while (level &gt; 0) {
                  const prevHeader = parent.prev(&quot;h&quot; + level);
                  const text = prevHeader.text();
                  headerHierarchy.unshift({level, text});
                  level--;
              }
          }
          linkModel[&quot;#&quot; + id] = {originalId: id, count: count++, headerHierarchy};
      }
  });
  </code></pre>
  <p>What am I doing wrong, since</p>
  <pre class="lang-js prettyprint-override"><code>const prevHeader = parent.prev(&quot;h&quot; + level);
  const text = prevHeader.text();
  </code></pre>
  <p>always returns an empty string (i.e. <code>&quot;&quot;</code>)?</p>