Getting character offset inside nested html tags

I have HTML code similar to this:

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

I would like to get the "mystery" character offset relative to the pre tag using Javascript (native or MooTools). I can get it relative to the span tag using the anchorNode property, but I can't find a way to get it relative to the pre tag.

0
source share
2 answers

You can use the DOM Range :

 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); 

Cautions:

  • This will work in all major browsers except IE <= 8. If you need a solution for IE, I can provide it.
  • This function will count the characters inside the <script> or <style> tags and invisible elements (for example, hidden CSS display: none ).
+8
source

you can write a method that calculates it using a recursive solution ... get the character offset for the secret, and then get the parent node for the range and get the range offset before it starts ... repeat until the desired tag is found (pre) or until until you finish the tags

0
source

Source: https://habr.com/ru/post/897688/


All Articles