I want to get the text that I clicked on, so if I click on the word "mother" the log will only show the word "mother" even though it is within a span that contains another word,
I used this code but it doesn't even select the span:
function getSelectedText(e) { if(window.getSelection) return console.log(window.getSelection().toString()); else if(document.getSelection) return console.log(document.getSelection()); else if(document.selection) return console.log(document.selection.createRange().text); return console.log(""); } document.body.onmouseup = getSelectedText;
<div class="destination"> <span class="word">sister mother</span> <span class="word" >brother</span> <span class="word" >father</span> </div> <h1>hi</h1>
P粉8514014752024-03-20 11:22:07
span-split option works in all browsers and does not require the use of third-party libraries.