Why javascript doesn't execute the querySelector inside AJAX?

I am trying to handle an HTML part inside the ajax success:function(data){} but for some reason the code won’t execute when I am calling it. Below is the code I tried:

  data:{limit:limit, start:start},
   var data_parse = JSON.parse(data);
   for (var i in data_parse){
        var divData = '<a id="default-like-'+data_parse[i].ID+'" href="#/" class="post__action post__action--reaction reaction reaction__toggle reaction-toggle--'+data_parse[i].ID+' reaction-emoticon-0 js-reaction-toggle" style="display: none;">\n'+
   if(data == '') {
     //Do nothing
     action = 'active';
   }else {
     $('#activitystream-loading').css("display", "block");
       action = 'inactive';
          var els1 = document.querySelectorAll(".post__action--reaction");
          for (var x = 0; x < els.length; x++){
            alert("Hey there")
            els1[x].style.display = 'block';

So, I also tried two ways. First of all, I tried to execute the code inside the complete:function(){} of AJAX and secondly, I tried to add the code inside this window.onload = function(){} but still nothing happening. There is not even any errors in the console, it just shows nothing. Do you know how can I handle the generated html part? Thanks in advance!

>Solution :

One possible reason why your code is not executing as expected is that you are using the wrong variable name in the for loop. In the line:

for (var x = 0; x < els.length; x++){

you are using the variable "els" instead of "els1". This might be causing the loop to not execute at all, thus leading to no output.

Try changing the variable name in the for loop to match the variable name used earlier in the code, like this:

for (var x = 0; x < els1.length; x++){

This should fix the issue and allow your code to execute properly.

Leave a Reply