title: How do you find the (string) length of a starting tag or ending tag?
body: <p>I'm trying to write a jQuery or pure Javascript function (preferring the more readable solution) that can count the length of a starting tag or ending tag in an HTML document.</p>
  
  <p>For example,</p>
  
  <pre><code>&lt;p&gt;Hello.&lt;/p&gt;
  </code></pre>
  
  <p>would return 3 and 4 for the starting and ending tag lengths. Adding attributes,</p>
  
  <pre><code>&lt;span class="red"&gt;Warning!&lt;/span&gt;
  </code></pre>
  
  <p>would return 18 and 7 for the starting and ending tag lengths. Finally,</p>
  
  <pre><code>&lt;img src="foobar.png"/&gt;
  </code></pre>
  
  <p>would return 23 and 0 (or -1) for the starting and ending tag lengths.</p>
  
  <p>I'm looking for a canonical, guaranteed-to-work-according-to-spec solution, so I'm trying to use DOM methods rather than manual text manipulations. For example, I would like the solution to work even for weird cases like</p>
  
  <pre><code>&lt;p&gt;spaces infiltrating the ending tag&lt;/ p &gt;
  </code></pre>
  
  <p>and</p>
  
  <pre><code>&lt;img alt="unended singleton tags" src="foobar.png"&gt;
  </code></pre>
  
  <p>and such. That is, my hope is that as long as we use proper DOM methods, we should be able to find the number of characters between <code>&lt;</code> and <code>&gt;</code> no matter how weird things get, even</p>
  
  <pre><code>&lt;div data-tag="&lt;div&gt;"&gt;HTML-like strings within attributes&lt;/div&gt;
  </code></pre>
  
  <p>I have looked at the jQuery API (especially the Manipulation section, including DOM Insertion and General Attributes subsections), but I don't see anything that would help.</p>
  
  <p>Currently the best idea I have, given an element <code>node</code> is</p>
  
  <pre><code>lengthOfEndTag = node.tagName.length + 3;
  
  lengthOfStartTag = node.outerHTML.length
                   - node.innerHTML.length
                   - lengthOfEndTag;
  </code></pre>
  
  <p>but of course I don't want to make such an assumption for the end tag.</p>
  
  <p>(Finally, I'm familiar with regular expressions&mdash;but trying to avoid them if at all possible.)</p>
  
  <hr>
  
  <p><strong>EDIT</strong></p>
  
  <p>@Pointy and @squint helped me understand that it's not possible to see <code>&lt;/ p &gt;</code>, for example, because the HTML is discarded once the DOM is created. That's fine. The objective, adjusted, is to find the length of the start and end tags <em>as would be rendered in <code>outerHTML</code></em>.</p>