Home > Blockchain >  select text inside span on click
select text inside span on click

Time:01-08

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 >
  <span >sister mother</span>
  <span  >brother</span>
  <span  >father</span>
</div>

<h1>hi</h1>

CodePudding user response:

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>

CodePudding user response:

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>

  • Related