onclick on selected elements and non selected elements jquery

In the following jquery code how can I include onclick event on <p>Click D3</p>, I included d1 and d2’s onclick p. I dont know how to include <p>Click D3</p> click event in the same statement i.e. $(".d1,.d2").on('click','p',function(){

$(".d1,.d2").on('click','p',function(){
  console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d1">
  <p>Click D1</p>
</div>
<div class="d2">
  <p>Click D2</p>
</div>
<p>Click D3</p>

Answer

If you do parent.on('click', element, function (){}) then you can’t really do anything but add a div (.d3) and select the p inside that.. if you don’t have any other p tags, then you could change the event listener to : $("body").on('click', 'p' ,function (){ console.log($(this).text()); }); OR You could wrap all of these p tags inside one div too

$(".d1, .d2, .d3").on('click','p',function (){
  console.log($(this).text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d1">
  <p>Click D1</p>
</div>
<div class="d2">
  <p>Click D2</p>
</div>
<div class="d3">
<p>Click D3</p>
</div>

Leave a Reply

Your email address will not be published. Required fields are marked *