javascript - 查找与所选文本匹配的 DOM 选择器集

标签 javascript html algorithm css-selectors textselection

假设你去了某个地方并选择了一些文本:

enter image description here

当您查看 DOM 时,它位于此处:

enter image description here

但实际上是这段文字:“Local embassy – For Wikipedia”,调试器不太正确。

我想知道的是如何从根本上找到与所选文本最匹配的选择器集。所以在突出显示方面,你会得到这个:

<b><a href="/wiki/Wikipedia:Local_Embassy" title="Wikipedia:Local Embassy">Local embassy</a></b> – For Wikipedia

它应该从这个简单的文本选择函数开始:

function getSelectionText() {
  var text = ''
  if (window.getSelection) {
    text = window.getSelection().toString()
  } else if (document.selection && document.selection.type != 'Control') {
    text = document.selection.createRange().text
  }
  return text
}

(解决这个问题):

enter image description here

...到一个函数,而不是返回匹配文本的选择器集,比如:

parent == '#mp-other-content li'
selectors relative to parent ==
  [
    'b',
    '#text'
  ]

想知道如何正确地做到这一点。不知道如何让调试器突出显示文本,只是想知道如何获取所选文本并返回与其最匹配的选择器。

最佳答案

tldr; var mySelectionHtmlElement = window.getSelection().anchorNode.parentElement;

这应该有效。从那里您可以浏览 DOM。 如果您只选择文本而不是链接或链接和文本的一部分,您应该得到 <li>作为 parent 。如果您只选择链接文本,您将获得 <a>作为 parent 。

$('body').on('mouseup', event => {
	console.log('selection text',window.getSelection().toString());
  console.log('selection node', window.getSelection());
  console.log('selections parent html element', window.getSelection().anchorNode.parentElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<b><a href="www.google.com">My Link</a></b>
- my followup text
</li>
</ul>

关于javascript - 查找与所选文本匹配的 DOM 选择器集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53086440/

相关文章:

algorithm - 在大稀疏矩阵中找到 "largest"稠密子矩阵

c - 基数排序中的位函数

将方法作为回调传递的 javascript 问题

javascript - Bootstrap 如何在同一窗口中显示所选图像(来自 img src ="")?

javascript - 如何在Ajax上更新数据属性完整

html - 当我在其内容的第一个数字处有一个数字时,跨越边界半径问题(在 chrome 中)

html - 保留 CSS 动画颜色填充

html - 如何避免 th 元素从 IE6/7 中的 tr 元素继承属性

algorithm - 搜索引擎不精确计数(大约 xxx 结果)

javascript - Firebase 中未找到 if 语句变量 == null?