Skip to content
Advertisement

jQuery process dynamically added anchor tags isn’t working

jQuery doesn’t process dynamically added anchor tags. The <li> <a> tags are added more dynamically. The below code works to add attributes for the anchor’s tags that are already there but more pagination is added by XHR AJAX calls and the .each() function doesn’t work.

$(document).ready(function () {
  $("ul.page-selector-list li a").each(function () {
    var pageText = $(this).text();
    $(this).attr("aria-label", "click here for " + pageText);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<ul class="page-selector-list">
  <li class="page-selector-item-first inactive"><a href="#">First</a></li>
  <li class="page-selector-item-previous inactive"><a href="#">Previous</a></li>
  <li><a class="page-selector-item-link active" data-offset="0" data-itemnumber="1" href="#">1</a></li>
  <li><a class="page-selector-item-link" data-offset="10" data-itemnumber="2" href="#">2</a></li>
  <li><a class="page-selector-item-link" data-offset="20" data-itemnumber="3" href="#">3</a></li>
  <li><span class="page-selector-more">...</span></li>
  <li><a class="page-selector-item-link" data-offset="2020" data-itemnumber="203" href="#">203</a></li>
  <li class="page-selector-item-next"><a href="#">Next</a></li>
  <li class="page-selector-item-last"><a href="#">Last</a></li>
</ul>

Advertisement

Answer

Please try below code when you find your code is not working after AJAX:

$( document ).ajaxComplete(function() {
    $('ul.page-selector-list li a').each(function(){
       var pageText = $(this).text();
       $(this).attr('aria-label', 'click here for '+ pageText);
    });
});

Please let me know if you find any issues.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement