skip to Main Content

In this way, I was trying to select the a tag but it has not been selected. How can I do this?

<!DOCTYPE html>
  <html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
      (function($) {
        var test = $('.page_item').find('> a').text();
        alert(test);



      })(jQuery)
    </script>
  </head>

  <body>
    <li class="page_item page-item-24">
      <a href="http://localhost/techblog/contac-us/">Contac us</a>
    </li>

  </body>

  </html>

3

Answers


  1. Why not just add this to the selector, istead of using find?

    $('.page_item > a').text()
    

    Also it would be as following with find method:

    $('.page_item').find('a').text();
    
    Login or Signup to reply.
  2. Just make it easier for yourself by adding an ID to the a element:

    <a id="js-contact-us" href="http://localhost/techblog/contac-us/">Contac us</a>
    

    Then:

    $('#js-contact-us').text()
    

    EDIT

    Note: Your code as written WORKS. (However inelegant it might be.)

    Are you sure it’s only executing once the DOM is ready (the HTML has been parsed?). If you run it as it is in your example, the script will run before the HTML is loaded.

    Move the script tag to before the closing body tag, or add defer, or wrap it in the DOMContentLoaded:

    document.addEventListener('DOMContentLoaded', () => {
        $('#js-contact-us').text()
    });
    
    Login or Signup to reply.
  3. the script should be after elements , your html should look like this :

    <!DOCTYPE html>
      <html>
    
      <head>
            <!-- meta tags and title -->
      </head>
    
      <body>
        <li class="page_item page-item-24">
          <a href="http://localhost/techblog/contac-us/">Contac us</a>
        </li>
    
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script>
          (function($) {
            var test = $('.page_item > a').text();
            alert(test);
    
          })(jQuery)
        </script>
    
      </body>
    
      </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search