简体   繁体   中英

getElementById from Object.keys(data)

I have simple Ajax codes, parsing Json data and filling dynamic divs inside. And I have problem when I want to get dynamically getElementById .

My key array returns successfully = ["blue","red","etc"..] and I have blue-data, red-data, etc-data div ids.

<div id="blue-data">myblue</div>
<div id="red-data">myred</div>
<div id="etc-data">myetc</div>

My codes are below:

      success: function(data) {
      Object.keys(data).forEach(function(key,index) {


            console.log(document.getElementById(''+key+'-data').innerHTML);


         });

});

When I run gives:

console.log(document.getElementById(''+key+'-data').innerHTML);

Line

Error

null is not an object (evaluating 'document.getElementById(''+key+'-data').innerHTML')

But in console, output is;

myblue
myred
myetc

How can I fix this? I want to get with key-data div inside values.

If your returned data is an Array, as you say, then Object.keys is not what you should use as it is for iterating over the properties (keys) of Objects. If you just have an Array, just loop over it directly:

 // This is just simulating the result of your `success` handler's argument: let data= ["blue","red","etc"]; // This would be INSIDE of your success callback function data.forEach(function(item) { console.log(document.getElementById(item + '-data').textContent); }); 
 <div id="blue-data">myblue</div> <div id="red-data">myred</div> <div id="etc-data">myetc</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM