admin管理员组文章数量:1425801
I've got HTML code similar to this one:
<pre>
words words words
words <span> words mystery words</span>
words words words
</pre>
I'd like to get the character offset of "mystery" with respect to the pre tag using Javascript (native or MooTools). I can get it with respect to the span tag using the anchorNode property, but I can't find a way to get it with respect to the pre tag.
I've got HTML code similar to this one:
<pre>
words words words
words <span> words mystery words</span>
words words words
</pre>
I'd like to get the character offset of "mystery" with respect to the pre tag using Javascript (native or MooTools). I can get it with respect to the span tag using the anchorNode property, but I can't find a way to get it with respect to the pre tag.
Share Improve this question asked Mar 31, 2011 at 23:52 sslepiansslepian 1,9215 gold badges21 silver badges27 bronze badges 1-
The
<span>
tags are there. Are they counted as characters? – BoltClock Commented Mar 31, 2011 at 23:54
2 Answers
Reset to default 9You could use a DOM Range
to do this:
function getCharOffsetRelativeTo(container, node, offset) {
var range = document.createRange();
range.selectNodeContents(container);
range.setEnd(node, offset);
return range.toString().length;
}
Example:
var sel = window.getSelection();
var pre = document.getElementById("your_pre_id");
var offset = getCharOffsetRelativeTo(pre, sel.anchorNode, sel.anchorOffset);
Caveats:
- This will work in all major browsers except IE <= 8. If you need a solution for IE then I can provide it.
- This function will count characters inside
<script>
or<style>
tags and invisible elements (hidden by CSSdisplay: none
, for example).
you could write a method that calculates it using a recursive solution...get the character offset for to mystery, and then get the parent node for span and get the offset of span to the beginning...repeat until the desired tag is found (pre) or until you run out of tags
本文标签: javascriptGetting character offset inside nested html tagsStack Overflow
版权声明:本文标题:javascript - Getting character offset inside nested html tags - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745391069a2656600.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论