如何以给定的偏移量获取HTML字符串中的父元素? [英] How to get the parent element in an HTML string at a given offset?

查看:103
本文介绍了如何以给定的偏移量获取HTML字符串中的父元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用JavaScript的方法来获取HTML字符串中给定位置的父元素(例如document.innerHTML或document.body.innerHTML).

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

简单的例子:

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

给定偏移量35(至48),该函数应返回"a"元素的节点对象.我想知道这是否完全可能,如果可以的话,什么是解决这个问题的好方法.

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.

在此先感谢您的努力!

是否可以使用Firefox在HTML文档中以给定的偏移量突出显示文本?

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?

我认为,一旦有了正确的父节点,添加突出显示就不会成为问题,因为这仅仅是DOM操作.

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?

说明:偏移量是相对于body标签内容的.感谢@乔纳森(Jonathan)指出了这一点.

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

非常感谢您.

推荐答案

查看的来源搜索并突出显示Java语言,它可能是您入门的好地方.

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

这篇关于如何以给定的偏移量获取HTML字符串中的父元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆