ncox85 ncox85 - 1 year ago 59
Ajax Question

How to change a dynamically created element after it loads javascript

I have a site that makes an HTTP request for JSON data, then a callback function processes the data and displays it by creating a series of divs dynamically. What I want to do is to wait for that function to finish adding the divs to the page, then apply labels only to specific divs created by the previous code.

HTTP Request and Callback

function data(callback){
var url = //request url;
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
document.body.className = 'ok';
//Parse returned string into an object, then pass the object to the callback function.
var data = JSON.parse(request.responseText);
} else {
document.body.className = 'error';
};"GET", url , true);
function dataDisplay(data){
//outputs <div id="1064" class="displayed-data">
<p id="message1" class="hidden"></p>

The code above displays my data exactly how I want it to, but when I try to access the numbered ID of the divs I want to change, the function runs before the data is displayed on the page, causing a 'null' error because the data I am trying to change hasn't been added to the DOM yet.

Second Function to change original

function label(){
var message1 = document.createTextNode('//some label');
var displayedData = document.getElementById('1064').getElementById('message1');

How do I get the second function to wait until the callback has completed before trying to access and change it? I tried a callback inside of a callback, something like:
but it still threw the same errors, so I clearly did it wrong. Sorry, I am brand new to JavaScript and don't really know where to go from here.

Thanks for your help!

Answer Source

A pretty quick way of doing it correctly is with this inline function.

data(function(result) {

Be aware that your data function itself completes very quickly - if you need something from its result, you will need to include it in its callback.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download