search

Home  >  Q&A  >  body text

Select text within span when clicked

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粉147747637P粉147747637243 days ago404

reply all(1)I'll reply

  • P粉851401475

    P粉8514014752024-03-20 11:22:07

    span-split option works in all browsers and does not require the use of third-party libraries.

     
            
        

    reply
    0
  • Cancelreply