Reputation: 79360
So say you go to some place and select some text:
When you look at the DOM it's around here:
But it's actually this text: "Local embassy – For Wikipedia"
, the debugger doesn't quite get it right.
What I'm wondering is how to essentially find the set of selectors that most closely match the selected text. So in terms of highlighting, you would get this:
<b><a href="/wiki/Wikipedia:Local_Embassy" title="Wikipedia:Local Embassy">Local embassy</a></b> – For Wikipedia
Somehow it should go from this simple text selection function:
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
}
(which resolves to this):
...To a function that instead returns the set of selectors that match the text, something like:
parent == '#mp-other-content li'
selectors relative to parent ==
[
'b',
'#text'
]
Wondering how to properly do this. Not wondering how to get the debugger to highlight the text, just how to get the selected text and return the selectors most closely matching it.
Upvotes: 1
Views: 66
Reputation: 141
tldr; var mySelectionHtmlElement = window.getSelection().anchorNode.parentElement;
This should work. From there you can navigate through the DOM.
If you select only the text not part of the link or link and text you should get the <li>
as parent. If you just select the links text you will get the <a>
as 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>
Upvotes: 1