Home > front end >  jquery on click $(document) working but $(element) not working
jquery on click $(document) working but $(element) not working

Time:10-14

When click $document is working, but click $element not working.

 $(document).on("click","p" ,function() {
        alert($(this).text());
 });

//$("p").on("click" , function() {
//alert($(this).text());
//});

 $(document).on("click","div" ,function() {
        alert($(this).text());
 });

// $("div").on("click" , function() {
//      alert($(this).text());
// });
<script src="https://code.jquery.com/jquery-3.6.1.slim.js" integrity="sha256-tXm sa1uzsbFnbXt8GJqsgi2Tw m4BLGDof6eUPjbtk=" crossorigin="anonymous"></script>

<p>Test</p>
<div>Test</div>     

Why $element is not working? I don't know why it doesn't work.

CodePudding user response:

It won't work in if the script is placed inside the head.

To make it work, place it inside the body just before the closing body tag.

If it's placed in the head tag do either of these

  1. Wrap the element click events inside jQuery.DOMReady event
  2. Add defer to the script tag(if it's an external file) like this.
<script defer src="path/to/script.js">
</script>
  • Related