-1

I want to get the text in which I clicked on, So if I click on word "mother" the log just show this word "mother", even if it's inside an span with another word,

I used this code but it doesn't even select the spans :

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>
user3840170
  • 26,597
  • 4
  • 30
  • 62
SOmeon
  • 13
  • 3
  • the code is set to console the words upon selection..which is working fine...if you want to select the text upon clicking then maybe you need to use onclick handler – buzz Jan 08 '23 at 07:18
  • this seems pretty complex, this might answer your question https://stackoverflow.com/questions/7563169/detect-which-word-has-been-clicked-on-within-a-text – Damzaky Jan 08 '23 at 07:31
  • Keep in mind that the `mouseup` event will not work on touchscreen-only devices. – user3840170 Jan 08 '23 at 08:39
  • Do you actually want ‘text in which I clicked on’, or do you want selection? Those are different things. – user3840170 Jan 08 '23 at 08:44

2 Answers2

0

The span-split option will work in all browsers and without using third-party libraries.

  <body>
        <style>
          .container{
              display: flex;
              gap: 5px;
              flex-wrap: wrap;
          }
      </style>
    <div id="root" class = "container"></div>
    <script>
      var text = 'Soon after this, I started working with Kitty, who has volunteered at the shelter for years, so she knew all the lay of the land and was super helpful.'
      var container = document.getElementById("root")
      text.split(' ').forEach((word)=>{
          var newWord = document.createElement("span")
          newWord.innerText = word
          newWord.className = 'myClass'
          container.appendChild(newWord)
      })
      function handler(event) {
          if (event.target.className === "myClass"){
              console.log(event.target.textContent)
          }
      }
      document.addEventListener('click',handler,false)
    </script>
  </body>
Solmeas
  • 11
  • 2
-1

function highlight(span) {
  span.classList.toggle("highlight");
  
  
  //select the text and do what ever
  var selectedText = span.innerHTML;
  alert(selectedText);
}
.highlight {
  background-color: lightblue;
}
<span onclick="highlight(this)">sister mother</span>
<span onclick="highlight(this)">brother</span>
<span onclick="highlight(this)">father</span>
Muhammad Zakaria
  • 1,269
  • 6
  • 14