Add JSON output to HTML ID

Viewed 163

I am using jQuery to read a JSON file and add the output to HTML IDs. So far everything works, but only as long as I output all IDs afterwards. However, if I now omit an ID from the output, for example, all the IDs defined below it are no longer output. Why does this happen?

$(document).ready(function() {
    function update_data() {
        $.getJSON("https://example.com/example.json", function(Data) {
                    
            // Example 1
            document.getElementById('example1').innerHTML = Data.example1;
                            
            // Example 2
            document.getElementById('example2').innerHTML = Data.example2;
                    
            // Example 3
            document.getElementById('example3').innerHTML = Data.example3;
        });
    }
update_data();
setInterval(update_data, '30000');
});

https://example.com/example.json returns something like this in my case:

{
    "example1": 725725,
    "example2": 47875,
    "example3": 04257
}

If I want to output all 3, it does so. But if I want to output only example1 and example3, it does it only for example1. Why is that?

Does work:

<div id='example1'>Load</div>
<div id='example2'>Load</div>
<div id='example3'>Load</div>

Works only for example1:

<div id='example1'>Load</div>
<div id='example3'>Load</div>
1 Answers

you have to test if id exists: test the length for example

function update_data() {
    $.getJSON("https://example.com/example.json", function(Data) {
                
        // Example 1
        if($('#example1').length){
           document.getElementById('example1').innerHTML = Data.example1;
         }               
        // Example 2
        if($('#example2').length){                       
            document.getElementById('example2').innerHTML = Data.example2;
        }        
        // Example 3
        if($('#example3').length){
           document.getElementById('example3').innerHTML = Data.example3;
        }
    });
}
Related