How to get the parent element in an HTML string at a given offset?

╄→尐↘猪︶ㄣ 提交于 2020-01-04 10:50:39

问题


New Question

I am looking for a way in Javascript to get the parent element of a given position in an HTML string (e.g. document.innerHTML or document.body.innerHTML).

Simple example:

<p>I really <em>like <a href="...">stackoverflow</a></em> a lot.</p>
                                   ^...........^
                               Offset 35  to  48

Given offset 35 (to 48), the function should return the node object of the "a" element. I am wondering whether this is possible at all and, if it is, what would be a good approach to solve this.

Thanks in advance for your efforts!


Old Question

Is there a way to highlight text at a given offset in an HTML document with Firefox?

I have a list of offsets and lengths of strings to highlight. I suppose I need to find out the parent element of the text node at the given offset, is this right?

I don't think it should be a problem for me to add the highlighting once I've got the right parent node, since this is simply DOM manipulation.

Do you have any ideas or hints?

Clarification: The offsets are relative to the contents of the body tag. Thanks @ Jonathan for pointing this out.

Thank you very much.


回答1:


check out the source of Search and Highlight With Javascript, it may be give you a good place to start.



来源:https://stackoverflow.com/questions/908477/how-to-get-the-parent-element-in-an-html-string-at-a-given-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!