javascript - How to add a listener to a div that is created after page load? -


i have looked other similar questions here , looks event delegation using on() sort of in direction need.

i have anchor user clicks generate dropdown menu. menu, through css, appears below link, in dom new div dropdown generated outside of 'scope' of div in anchor resides. it's this:

before selection:

<body>     <div>         <!-- load of other nested divs -->         <div class="menu">             <a href="#" id="clickanchor">select list</a>         </div>     </div> </body> 

after selection:

<body>     <div>         <!-- load of other nested divs -->         <div class="menu">             <a href="#" id="clickanchor">select list</a>         </div>     </div>     <div class="selected">         <ul>             <li>...</li>             <!-- lots of these -->         </ul> </body> 

i used <!-- load of other nested divs --> indicate 'menu' nested deep within first body div.

what want when 'selected' appears want append class it. can reuse dropdown menu in other places. can't access class 1 or both of 2 reasons:

1] it's added dynamically jquery add class has finished running on page load. can't use $(".selected").on("click", function(event){} not clicking 'selected', rather clicking 'clickanchor', unsure how access 'selected' way.

2] following above, when have tried $("#clickanchor").on("click", function(event){}nothing happening either - because new div created direct child of <body>, rather child of 'menu'? in other words scope of click event? (probably wrong here).

attempt @ mockup if don't have control on appending div.

$("#clickanchor").on("click", function() {     // code append div     settimeout(function() {         var div = $(".selected");         // add code add class     }, 0); }); 

if set timeout 0ms, it'll queued execute after dom has catched inserting div, should able select it. alternatively, can put promise on execution of select2.js script? won't need timeout.


Comments