Click on the span to choose the text within it

I am looking to retrieve the specific text that was clicked on. For example, if I click on the word "mother," I want the log to display just that word "mother" even if it is contained within a span with other words.

The code I have tried doesn't seem to 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>

Answer №1

The option of span splitting is compatible with all browsers and does not require the use of external 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>

Answer №2

function addHighlight(span) {
  span.classList.toggle("highlight");
  
  //get the selected text
  var highlightedText = span.innerHTML;
  alert(highlightedText);
}
.highlight {
  background-color: lightblue;
}
<span onclick="addHighlight(this)">sister mother</span>
<span onclick="addHighlight(this)">brother</span>
<span onclick="addHighlight(this)">father</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to isolate JSON data based on a specific field?

Just dipping my toes into the world of JS and JSON. I've got this JSON data: { "month":"november", "category":"coffee", "price":50, "name":"Pike Place Roast Brewed Coffee Verismo Pods", "flavor":"flavored", "count ...

Delay the fading in of an element using jQuery

Is there a way to remove the pause between the images in my JavaScript/jQuery slideshow when fading in and out? I attempted using a small delay, but it still didn't eliminate the blank space. Any suggestions? Check out the code on jsfiddle: https://j ...

Incorporating personalized cells within Row Formatter in Tabulator

I'm currently experimenting with Tabulator (specifically React-Tabulator) to create a proof of concept for my project. One of the requirements for my project is to include buttons within the sections of my data trees. For example, I have departments ...

Unable to attach numerous parameters to the content of the request

I am encountering an issue with my code where I have two classes and need to call two separate models using two store procedures to insert data into both tables. The controller is set up like this: [HttpPost] public IHttpActionResult AddData([FromBody]ILi ...

What is the best way to transform the content within a div into accordion tabs exclusively for display on mobile devices?

Looking for a way to make a div and its content into clickable accordion tabs for mobile users. However, the current setup is too wide for desktops and covers too much area on mobile devices. The goal is to allow guests to click on the accordion tab to ex ...

Is there a cutting-edge javascript/jquery tool that enables SQL-type queries on JSON datasets?

About a year ago, this question was posed on Stack Overflow. After searching extensively for answers, it seems that all the libraries I've come across have not been updated in over a year. I'm curious if anyone knows of any currently maintained l ...

The Fetch API's Post functionality is currently experiencing issues

fetch('http://localhost:9000/api/app/contact', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email: this.state.email, contactNumber: ...

Can we define a style or CSS for one element depending on the characteristics of another element?

One challenge I'm facing involves a 3rd party library (fullcalendar) that automatically sets the height of elements based on internal calculations to ensure they look good in any viewport: <div style="height: 72px;"> Unfortunately, not all ele ...

What is the easiest way to create a star pattern using JavaScript?

I attempted the following code but the output is incorrect! for(i=5;i>=1;i--) { for(j=i;j>=1;j--){ console.log(j); } console.log("\n"); } ...

Using Immutable JS to Generate an OrderedMap from a List

I possess a List const results = [94, 88, 121, 17]; and I also own a Map const posts = { 94: { title: 'Foo bar', content: 'Blah blah blah...' }, 88: { title: 'Bar Foo', content: 'Blah blah blah...' }, 121 ...

Searching for text within an HTML document using Selenium in Python can be easily achieved by using the appropriate methods and

Is there a way to find and retrieve specific texts within an HTML file using Selenium in Python, especially if the text is not enclosed within an element? <div class="datagrid row"> ==$0 <h2 class="bottom-border block">Accepted Shipment</h ...

The Ajax request encountered a syntax error due to an unexpected token '<'

I have searched the forum extensively for similar questions, but unfortunately haven't found a suitable answer for my specific problem. In my jQuery code, I am attempting to make an AJAX call using the following snippet: function submitForm(formData) ...

Exploring the Implementation of Conditional Logic Using Variables in ReactJS

I have a current project in Reactjs where I am extracting the current url/hostname. My goal is to utilize this URL within an if-else statement - meaning, if the url="/" (home page) then display the first header, otherwise display the second hea ...

Tips for deploying a Nuxt application using an alternative command line interface

Despite my best efforts scouring the internet for a solution, I have yet to find a method to resolve my issue. The problem lies with my nuxt.js SPA being blocked by my company firewall when accessed by other users at the designated host/port. While servin ...

Issues with JavaScript Array Splice Function

var cache = []; cache[0] = "0"; cache[1] = "1"; cache[2] = "2"; cache[3] = "3"; cache[4] = "4"; cache["r"] = "r"; console.log(cache.length); for(key in cache){ if(isNaN(key))continue; else cache.splice(key,1); // The functionality of cache.splice(k ...

What are the best scenarios for utilizing (a)synchronous calls?

Currently, I am working on a project for my office as a learning exercise. We have a tradition of bringing food every Monday, so I decided to create a program that displays each person's turn. My webpage can generate a calendar with a spare color colu ...

Utilizing SASS in Eclipse for Java EE Development

Although I have already looked at this Stack Overflow question, it did not provide the solution I am seeking. As a Java Web Developer, I have been utilizing Less for my CSS pre-processing needs. However, I am now interested in transitioning to Sass due to ...

Generate a unique 4-6-4 pattern using React JS

Hello everyone, I am just starting out with react JS. Can someone please guide me on how to re-format a random string into a 4-6-4 format, using only numbers and A-Z characters? Requirement: When the Submit button is clicked, I need to generate an Access ...

Tips for detecting HTML updates using Python requests

My goal is to monitor a page for updates while maintaining the same session and cookies, without sending a completely new request. How can I determine if there are HTML updates within my current request? The page will redirect but keep the same URL. This ...

Ways to track a moving div element using jQuery animations on the screen

I've been experimenting with animating a graphic along a curved path using jQuery.crSpline and I'm quite pleased with the outcome. The only issue is that the canvas size is intentionally set to be wider than most screens, causing the graphic to ...