window.getSelection() doesn't give html nodes
-
28-06-2021 - |
Question
This is my page source :
<body>
<div>
<p><span id="1">word</span> <span id="2">word</span> </p>
<div><span id="3">word</span> <span id="4">word</span></div>
<ul>
<li><span id="5">word</span> <span id="6">word</span></li>
</ul>
</ul>
<p><span id="7">word</span> <span id="8">word</span> <strong><span id="9">word</span></strong> </p>
</div>
</body>
I want to highlight(apply a new class) user selected spans and get it id's.
I can get user selected content through window.getSelection().But i don't know how to get selected text nodes.
Thanks in advance, Logan
Solution
The window.getSelection()
returns a selection
object (ref) that includes the start (anchorNode
) and end (extentNode
). So based on the HTML you provided - with the ID's modified to not using only numbers (ref) - here is a demo. Click on any word, or select a group of words to see them get the "red" class name.
Modified HTML
<div>
<p><span id="s1">word1</span> <span id="s2">word2</span> </p>
<div><span id="s3">word3</span> <span id="s4">word4</span></div>
<ul>
<li><span id="s5">word5</span> <span id="s6">word6</span></li>
</ul>
<p><span id="s7">word7</span> <span id="s8">word8</span> <strong><span id="s9">word9</span></strong> </p>
</div>
Script
$('div').bind('mouseup', function(){
var i,
s = window.getSelection(),
// get ID of starting node
start = parseInt((s.anchorNode.parentNode.id || '').substring(1), 10),
// get ID of end node
end = parseInt((s.extentNode.parentNode.id || '').substring(1), 10),
// start gathering spans
spans = $('#s' + start);
// remove selected class
$('span[id^=s]').removeClass('red');
// add each span
for (i = start; i <= end; i++) {
spans = spans.add( $('#s' + i) );
}
// add selected class
spans.addClass('red');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow