skip to Main Content

I am trying to display a new div element added to the DOM via AJAX.

So, via AJAX/PHP I added dynamically some new buttons

<button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index.')">View</button>

And also added dynamically some new hidden divs

<div id="viewPP_'.$index.'" style="display: none;">

In my main page I have a JS function (before the $(document).ready) to show/hide the div

function viewPP(i){
    
var obj = "viewPP_"+i;
    
document.getElementById(obj).style.display = "block";
//$(obj).toggle();

}    

If I use document.getElementBy... , nothing happens. (no error, just do nothing)

If I use $(obj), nothing happens (no error, just do nothing)

I can understand new elements added to the DOM after the page is loaded are not recognized by JQuery, but can’t find the way to make it work.

How can I do that??

3

Answers


  1. Chosen as BEST ANSWER

    I noticed the buttons and divs had the same id, so I fixed them and now work.

    Here's the working code, hope it helps someone in the future.

    Thanks everyone for your help!

    JS

    function viewPP(i){   
      var obj = "#dataPP_"+i;
      $(obj).toggle();
    } 
    
    $(document).ready(function(){
        $.ajax({
           ...
        });
    });
    

    PHP Response to AJAX Request

    print '<button type="button" id="viewPP_'.$index.'" onclick="viewPP('.index.')">View</button>';
    
    print '<div id="dataPP_'.$index.'" style="display: none;"></div>';
    

  2. Remove that #, when declaring obj. When you are using getElementById method, you just need to specify id, without #, as you would use in CSS or querySelector method.

    function viewPP(i){
        
    var obj = "viewPP_"+i;
        
    document.getElementById(obj).style.display = "block"
    
    }    
    

    If this is not it, there is something going on with loading these elements…

    Login or Signup to reply.
  3. One approach could be that, you can add a fix dpm element which can act as parent dom element for your dynamic dom element.
    By this approach you can fetch child nodes of fixed dom parent node.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search