Take the 2-minute tour ×

I've got HTML code similar to this one:

    words words words
    words <span> words mystery words</span>
    words words words

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
The <span> tags are there. Are they counted as characters? –  BoltClock Mar 31 '11 at 23:54
They shouldn't be counted. –  sslepian Mar 31 '11 at 23:58
add comment

2 Answers

up vote 1 down vote accepted

You could use a DOM Range to do this:

function getCharOffsetRelativeTo(container, node, offset) {
    var range = document.createRange();
    range.setEnd(node, offset);
    return range.toString().length;


var sel = window.getSelection();
var pre = document.getElementById("your_pre_id");
var offset = getCharOffsetRelativeTo(pre, sel.anchorNode, sel.anchorOffset);


  • 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 CSS display: none, for example).
share|improve this answer
Looks pretty good so far, thanks. –  sslepian Apr 1 '11 at 19:04
add comment

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

share|improve this answer
add comment

Your Answer


