"JavaScript, don't forget the variable and remove the div element

Currently, I have a script that adds a word to a div on mouse-over. Now, my goal is to have the word remembered and printed in the console when clicking on it. However, the words are links formatted like this:
<a href"">So,</a>
When clicked, the script currently remembers the entire link. Therefore, I need to figure out a way to extract just the word "So". Any suggestions? Here's the code snippet:

<script src="https://code.jquery.com/jquery-2.2.4.js"></script>

<script>
var $allescheissehierrein = $('.allescheissehierrein'),
    database = {
    1: '<a href="file:///Users/shirin/Desktop/A/Media%20Design/TCB/one.html">So,</a>', 
    2: '<a href="file:///Users/shirin/Desktop/A/Media%20Design/TCB/one.html">HERE,</a>'},
    symbol = '',
    placeRandomly = function () {
      var w = document.body.offsetWidth,
          h = document.body.offsetHeight,
          rd = document.getElementsByTagName('div');

      for (var c = 0, l = rd.length; c < l; c++) {
        if (rd[c].className !== 'random') {
          continue;
        }

        var xCoord = Math.floor(Math.random() * w),
            yCoord = Math.floor(Math.random() * h);

        switch (true) {
          case (xCoord >= w - rd[c].offsetWidth - 10):
            xCoord = w - rd[c].offsetWidth - 10;
            break;
          case (xCoord <= 10):
            xCoord = 10;
            break;
          case (yCoord >= h - rd[c].offsetHeight - 10):
            yCoord = h - rd[c].offsetHeight - 10;
            break;
          case (yCoord <= 10):
            yCoord = 10;
            break;
        }

        rd[c].style.left = xCoord + 'px';
        rd[c].style.top = yCoord + 'px';
      }
    };

//loop through 100 times or however many needed
for (var i = 1; i <= 2; i++) {

  //save a div in a variable
  //set "data-hover" attribute based on the incremented value which will be different each time
  switch (true) {
    case (i < 24):
      symbol = '#';
      break;
    case ((i > 23) && (i < 47)):
      symbol = '**';
      break;
    case ((i > 46) && (i < 97)):
      symbol = '-';
      break;
    case ((i > 96) && (i < 114)):
      symbol = '1.';
      break;
    case (i > 113):
      symbol = '~~';
      break;
  }

  //append this to the allescheissehierrein-div (100 times)
  $allescheissehierrein.append('<div data-hover="' + i + '" class="random"><p>' + symbol + '</p></div>');
}

//run placeRandom function only after placing all 100 divs because they do not exist before that
placeRandomly();

//implementation with jQuery AND database
$('.random')
  .hover(function () {
    var hoverData = $(this).data('hover'),
        dataFromDatabase = database[hoverData];
    $(this).append($('<span>' + dataFromDatabase + '</span>').show('slow'));


      $( 'a' ).mousedown( function( event )
  {
       var poemArray;
  if ( localStorage.getItem( "poem" ) )
  {
      poemArray = localStorage.getItem( "poem" );

      console.log( poemArray );
  }
  else
  {
      poemArray = "";
      localStorage.setItem( "poem", poemArray );
  }

  poemArray += " " + dataFromDatabase;

  console.log( poemArray );


  localStorage.setItem( "poem", poemArray );

  }
  )



  }, function () {
    $(this).find('span:last').remove();
  });











  </script>

</html>

Answer №1

To access the content within an anchor tag using jQuery, you can follow these steps:

var anchorText = $("a").text();

This code will retrieve the text inside the anchor tag. Alternatively, you can also use this approach,

var anchor = <a href="file:///Users/shirin/Desktop/A/Media%20Design/TCB/one.html">So,</a>

anchor.substring(indexOf(">")[0], indexOf("<")[1]);

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

Tips on displaying just two buttons in one line

When using *ngFor to display multiple buttons, all buttons appear in one column. I want to have only 2 buttons in a row: the green buttons in one line, and the red buttons in the next line. How can I achieve this? Here is what I have tried: <div class= ...

Avoid running getStaticPaths for a specific locale

Is there a way to prevent Next.js getStaticPaths from generating static pages for a specific locale? In my Next.js configuration: i18n: { locales: ['default', 'en', 'hu', 'de', 'cz', 'eu', ...

Is there a way to incorporate the ACE code editor into a Vue project without relying on its built-in Vue

Just starting out with Vue and I'm looking to incorporate the ace code editor (this package) into my project. However, I want to avoid using the vue2-component & vue3-component versions for learning purposes. How can I achieve this? What's t ...

Guide on how to Import a Google Apps Script using the Google Drive API with NodeJS

I've been attempting to utilize the Google API NodeJS client in order to upload a Google Apps Script to my drive. Even though I'm carefully following the instructions provided in the documentation, the file is only being uploaded as plain text ra ...

Type for the key in array.reduce that is not specific or unique

Given an array of objects, I use the reduce method to transform it into a new format where each key represents a date from the original array. For example, if the array contains objects with dates like {date: '22-02-06-00:55:66', name: 'one& ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

Navigating spaces, tabs, and line breaks during ReactJS rendering

I have been attempting to display a string in a ReactJS Dialog box, which contains spaces and newlines represented by /n /t characters. My goal is to show the text exactly as it is with all the spaces and line breaks preserved. Despite trying various metho ...

Problem with triggering a fire event on a Bootstrap carousel slide

I'm having trouble getting this code to trigger an event when the carousel slides. Any ideas on how to make it work? const $carousel = $('#carousel-showcase'); $carousel.carousel(); $carousel.on('slide', function(e) { setTimeo ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

JavaScript oddity with closure problems

Why did I receive ['undefined1','undefined2'] as the value for my array in this specific case, even though I pushed it in the same scope? router.post('/add', function(req, res) { var imageArr = []; for(var i = 1; i &l ...

What is the best way to adjust the canvas size within a list item?

I have successfully created a 3D model with Zdog that dynamically resizes based on the screen size. The model includes a dome and brim, which rotate smoothly as intended. Here is the code snippet: const TAU = Zdog.TAU; let hat = new Zdog.Illustration({ ...

How can we efficiently loop through all the icons in React Material-UI?

I am looking to iterate over all the icons from @material-ui/icons in a React application. If I want to import a single icon, I can do so like this import IconNameIcon from '@material-ui/icons/IconName' and then use it in my component like th ...

Issue encountered while fetching data from SQL database in a Node.js application

After successfully connecting the database to my node js project, I encountered an issue when attempting to retrieve data using the get operation. Despite the connection working fine, I was unable to resolve the error that occurred. Establishing the SQL c ...

Exploring cookies to extract and display my email using Express.js

I am currently working on retrieving the name and value fields as cookies through a loop in my app.get method, then posting the field values in the app.post method using expressjs. I would appreciate it if someone could review the 'for loop' bel ...

Tips for implementing import or require in Electron

Currently, I am in the process of developing an electron app. I would like to incorporate some functions from other JS files into my project. However, when attempting to use the import statement, an error is triggered "cannot use import statement outside a ...

How to smoothly scroll a child div when the parent div is set as position sticky in vue JS

My landing page requires a unique feature: when a user enters a specific <section>, that section should become fixed while the elements inside the corresponding <div> start scrolling. Once the inner div has finished scrolling, the parent <se ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...

Tips for showcasing cards in a horizontal inline layout

Hello everyone! I'm currently working on creating dynamic cards, but I'm having trouble displaying them inline. I'd like to arrange the cards horizontally with a scroll bar. https://i.sstatic.net/zqcua.png I want to make them display in ho ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

The behavior of Django Admin is rather peculiar

My Django app is running smoothly, but I've noticed some strange behavior in the Django Admin interface. When I click on a model, instead of being taken to the list of records for that model, I'm redirected to the same model list but with a pecul ...