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
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
PHP Response to AJAX Request
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.
If this is not it, there is something going on with loading these elements…
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.