简体   繁体   中英

How to select <a> tag using jQuery

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>

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();

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()
});

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM