necik11
necik11

Reputation: 33

How to trigger a click on a dynamically added element

This element is dynamically generated. Is it possible to trigger a click on the element?

<a unselectable="on" href="javascript:;" onclick="return false;" class="xxx" role="button" aria-haspopup="true">
  <span unselectable="on" class="xxx2">
    New<br>
    Item
    <span unselectable="on" class="xxx3">
      <img unselectable="on" src="xxx">
    </span>
  </span>
</a>

Upvotes: 0

Views: 96

Answers (2)

AshTyson
AshTyson

Reputation: 493

If you were trying to ask "Is it possible to attach a click on the element on dynamic elements?", then

$('body').on('click', function(evt) {
    // Check if its the proper element. Here its anchor tag with class 'xxx'
    if (evt.target.nodeName === 'A' && evt.target.classList.contains('xxx')) {
       // Anchor tag is clicked
    }
}, true);

If you have multiple elements which needs to be detected during the event bubbling, this will be useful.

Upvotes: 0

Deepak A
Deepak A

Reputation: 1636

Use trigger('click') to to achieve this ref http://api.jquery.com/trigger/ ,Hope this helps

$(document).on('click','.xxx',function(e){
   console.log('link has been clicked') 
})

$('.xxx').trigger('click')   // dynamic click event on link
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a unselectable="on" href="javascript:;" onclick="return false;" class="xxx" role="button" aria-haspopup="true"><span unselectable="on" class="xxx2">New<br>Item<span unselectable="on" class="xxx3"><img unselectable="on" src="xxx"></span></span></a>

Upvotes: 1

Related Questions