I am trying to write jQuery or a pure Javascript function (preferring a more readable solution) that can read the length of the source tag or end tag in an HTML document.
For instance,
<p>Hello.</p>
will return 3 and 4 for the initial and final tag lengths. Adding Attributes
<span class="red">Warning!</span>
will return 18 and 7 for the initial and final tag lengths. Finally,
<img src="foobar.png"/>
will return 23 and 0 (or -1) for the length of the start and end of the tag.
I am looking for a canonical solution guaranteed to work in accordance with the requirements, so I try to use DOM methods, rather than manual manipulations with the text. For example, I would like the solution to work even in such strange cases as
<p>spaces infiltrating the ending tag</ p >
and
<img alt="unended singleton tags" src="foobar.png">
etc. That is, I hope that as long as we use the correct DOM methods, we should be able to find the number of characters between < and > no matter how strange things turn out, even
<div data-tag="<div>">HTML-like strings within attributes</div>
I looked through the jQuery API (especially the Manipulation section, including the DOM subsections of Insertion and General Attributes), but I don't see anything that could help.
Currently, the best idea I got, given the node element, is
lengthOfEndTag = node.tagName.length + 3; lengthOfStartTag = node.outerHTML.length - node.innerHTML.length - lengthOfEndTag;
but of course I donβt want to make such an assumption for the final tag.
(Finally, I am familiar with the & mdash regular expressions, but try to avoid them, if at all possible.)
EDIT
@Pointy and @squint helped me understand that it's impossible to see </ p > , for example, because HTML is discarded after the DOM is created. It's great. The corrected goal is to find the length of the start and end tags that will be displayed in outerHTML .