skip to Main Content

Below is a sample of a URL that is in a site (project that I inherited).

When clicking on the link, I need to get the text "Click Link".

I have searched the web and all suggestions do not work.

Any help is appreciated.

 <a href="site/page" onclick="loadContent('https://site/page.com');">
   <span class="navitem">Click Link</span>
 </a>

The text in a span tag.

I’ve tried

$('. navitem').on('click', 'a', function() {
    var text = $(this).text();
});

But Console log says $ not defined.
I also tried

$('a').live('click', function() {
    window.location.href = $(this).closest('span').text();
});

3

Answers


  1. document.querySelector('a').addEventListener('click', function() {
        var text = this.querySelector('span').textContent
        
        // Do anything with text
        console.log(text)
    })
    
    Login or Signup to reply.
  2. In your following jQuery code:

    $('.navitem').on('click', 'a', function() {
        var text = $(this).text();
    });
    

    you have deleget event on a of navitem which in your case is incorrect. It need to be something like $('a').on('click', '.navitem'). I have update this click event in following snippet.

    $('.navitem').off("click").on('click', function(e) {
      e.preventDefault();
      var text = $(this).text();
      console.log(text);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <a href="site/page" onclick="loadContent('https://site/page.com');">
      <span class="navitem">Click Link</span>
    </a>

    Similarly, when using live method in your, second code you might get

    Uncaught TypeError: $(…).live is not a function

    this is because the live API is deprecated has been removed since jQuery 1.9

    Login or Signup to reply.
  3. Your first code snippet contains two misstakes. Change this one by

    $('.navitem').on('click', function ()
      {
          var text = $(this).text();
           window.location.href = text; //?? What eveer you want to do that 
      });
    

    There was an unnessacry space between ‘.’ and ‘navitem’. Another one was in the on method. I removed the passed parameter ‘a’.

    Based on your last comment – underneath your question- you have to wrap this into

    $(document).ready(function()
    {
    $('.navitem').on('click', function ()
      {
          var text = $(this).text();
           window.location.href = text; //?? What eveer you want to do that 
      }); 
    });
    

    Another point is your html code snippet. The presented code makes not sense:

    <a href="site/page" onclick="loadContent('https://site/page.com');">
    <span>...</span>
    </a>
    

    Your a tag overlaps you span tag and the href attribute overlaps the onclick attribute, so the value of href will be executed first. Your added code for span element won’t be executed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search